在Flex布局中将文本对齐为中心

时间:2019-06-04 05:45:06

标签: html css flexbox

如果要将文本对齐为div的中心或结尾,则需要显示省略号,如果文本长度超出div宽度,则为

下面的示例工作正常。

我的期望是:如果我们将item类添加到父div,它将像在span中应用的一样工作。

工作示例: 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;
});

2 个答案:

答案 0 :(得分:0)

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

.child {
 margin: auto;
  }

答案 1 :(得分:0)

您可以在此处应用最大宽度:90%; span.item以查看中心和伸缩端

var justify = document.getElementById("justifyMe");
justifyMe.addEventListener("change", function (evt) {
  document.getElementById("container").style.justifyContent = evt.target.value;
});
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;
  max-width:90%;
}

.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;
}
<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>