在换行符之后将flexbox内容居中

时间:2019-01-23 14:50:31

标签: css flexbox

我正在尝试在宽度有限的父元素内居中放置文本。但是,文本设置为大字体,这可能会导致换行。但是,元素换行并不会减小元素的宽度。如果文本不适合,是否可以将文本放在父包装中居中?

您可以在堆栈溢出代码示例中找到失败的示例。顶部的框有换行符,仍应居中。

.wrapper {
  width: 900px;
  margin: 0 auto;
  background: lightgrey;
}

.box {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 300px;
  height: 200px;
  border: 1px solid green;
 
}

.box:nth-child(1) {
    background: green;
    font-size: 45px;
  }
   .box:nth-child(2) {
    background: orange;
  }
<div class="wrapper">
  <div class="box"><h3>Lorem Ipsum</h3></div>
<div class="box"><h3>Lorem Ipsum</h3></div>
  </div>

2 个答案:

答案 0 :(得分:0)

只需添加text-align: center;

.wrapper {
  width: 900px;
  margin: 0 auto;
  background: lightgrey;
}

.box {
  display: flex;
  align-items: center;
  justify-content: center;
  /* text-align: center; */
  width: 300px;
  height: 200px;
  border: 1px solid green;
 
}
.box > * {
  flex: 0 0 50%;
}

.box:nth-child(1) {
    background: green;
    font-size: 45px;
  }
   .box:nth-child(2) {
    background: orange;
  }
<div class="wrapper">
  <div class="box"><h3>Lorem Ipsum</h3></div>
<div class="box"><h3>Lorem Ipsum</h3></div>
  </div>

答案 1 :(得分:0)

您可以将width:min-content;与第一个孩子(https://caniuse.com/#feat=intrinsic-width)一起使用

.wrapper {
  width: 900px;
  margin: 0 auto;
  background: lightgrey;
}

.box {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 300px;
  height: 200px;
  border: 1px solid green;
}
.box:nth-child(1) h3 {
 width:-webkit-min-content;
 width:-moz-min-content;
 width:min-content;
 border:1px solid;
}

.box:nth-child(1) {
  background: green;
  font-size: 45px;
}

.box:nth-child(2) {
  background: orange;
}
<div class="wrapper">
  <div class="box">
    <h3>Loreme Ipsum</h3>
  </div>
  <div class="box">
    <h3>Lorem Ipsum</h3>
  </div>
</div>

相关问题