首页 > 解决方案 > 在 flex 布局中将文本居中对齐

问题描述

如果我们想将文本对齐到 div 的中心或末尾,我们需要显示省略号,如果文本长度溢出 div 宽度。

下面的示例工作正常。

我的期望是:如果我们将项目类添加到父 div,它将像在跨度中应用的那样工作。

工作示例: https ://codepen.io/Muthupandi07/pen/oRVwqV

提前致谢。

HTML:

<div class="controls">
<select id="justifyMe">
  <option value="flex-start">flex-start</option>
  <option value="flex-end">flex-end</option>
  <option value="center">center</option>
</select>    
</div>

<div class="container" id="container">
  <span class="item">How to center an item using flexbox</span>      
</div>

CSS:

body {
  padding: 20px;
  font: 1em Helvetica Neue, Helvetica, Arial, sans-serif;
}

* {box-sizing: border-box;}

p {
  margin: 0 0 1em 0;
}

.container {  
  border: 5px solid rgb(111,41,97);
  border-radius: .5em;
  padding: 10px;
  display: flex;
  width: 200px;
}

.item {
  text-overflow: ellipsis;
  white-space: pre;
  overflow: hidden;
}

.controls {
  background-color: rgba(0,0,0,.1);
  padding: 10px;
  border-radius: .5em;
  border: 1px solid rgba(0,0,0,.2);
  margin: 0 0 2em 0
}

.controls select {
  font-size: .9em;
}

JS:

var justify = document.getElementById("justifyMe");
justifyMe.addEventListener("change", function (evt) {
  document.getElementById("container").style.justifyContent = evt.target.value;
});

标签: htmlcssflexbox

解决方案


 <div class="parent">
 <span class="child"> center me </span>
 <div>
.parent {
 display: flex;
 }

.child {
 margin: auto;
  }

推荐阅读