Центрирование содержимого flexbox после переноса строки - PullRequest
0 голосов
/ 23 января 2019

Я пытаюсь центрировать текст внутри родительского элемента ограниченной ширины. Однако текст выделен крупным шрифтом, что может привести к разрыву строки. Однако разрыв строки элемента не уменьшает ширину элемента. Есть ли способ центрировать текст внутри родительской оболочки, если текст не умещается?

Вы можете найти ошибочный пример в примере кода переполнения стека. Верхнее поле имеет разрыв строки и все еще должно быть по центру.

.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 голосов
/ 23 января 2019

Вы можете использовать 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>
0 голосов
/ 23 января 2019

Просто добавьте 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...