Чем обусловлена ​​разница в ширине гибкого элемента и элемента inline-block? - PullRequest
0 голосов
/ 20 февраля 2019

См. Эту скрипку:

https://jsfiddle.net/9hnj0b8v/3/

Единственное различие в двух элементах:

.label1
{
  display: inline-block;
}

.label2
{
  display: flex;
}

Таким образом, две метки идентичны, за исключением того, что одна установлена ​​навстроенный блок и один изгиб.Почему они имеют разную ширину?Почему один превышает свой контейнер, а другой нет?

Ответы [ 3 ]

0 голосов
/ 20 февраля 2019

Основное различие, которое я заметил, заключается в том, что с помощью inline-блока он будет заполнять ваш родительский div вашими inline-block элементами независимо от того, сколько элементов содержится в вашем родительском div, однако с display: flex разделит ширину вашего родительского div.(или высота) с номером элемента, который у вас есть.

Кроме того, в вашей скрипке вы уже установили inline-block для диапазона, просто попробуйте удалить его, и вы увидите разницу в болеевизуальный способ

0 голосов
/ 20 февраля 2019

Это из-за white-space:nowrap.

Без вас будет ожидаемый результат:

div {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 200px;
  background: #f0f0f0;
}

span {
  display: inline-block;
  white-space: normal;
  vertical-align: top;
}

label {
  margin-top: 10px;
  /*white-space: nowrap;*/
}

.label1 {
  display: inline-block;
}

.label2 {
  display: flex;
}
<div>

  <label class=label1>
 <input type=checkbox>
 <span>
  Here is a long description for the option that is set via the checkbox
  on the left. The label is set to inline-block. For some reason,
  it overflows the containing div. But why?
</span>
</label>


</div>

Обратите внимание, что ширина inline-block равна контейнеру, потому что там много текста, и он сломается, так что это похоже на width:100%.Затем, если вы добавите white-space:nowrap, вы просто отключите перенос и переместите этот inline-block верхний на , сохраняя его ширину , и вы создадите переполнение 1

div {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 200px;
  background: #f0f0f0;
}

span {
  display: inline-block;
  white-space: normal;
  vertical-align: top;
}

label {
  margin-top: 10px;
  white-space: nowrap;
}

.label1 {
  display: inline-block;
}

.label2 {
  display: flex;
}
<div>

  <label class=label1>
 <input type=checkbox>
 <span>
  Here is a long description for the option that is set via the checkbox
  on the left. The label is set to inline-block. For some reason,
  it overflows the containing div. But why?
</span>
</label>


</div>

Для flexbox все по-другому, поскольку обертывание контролируется flex-wrap, то есть по умолчанию nowrap.Обратите внимание, что inline-block внутри контейнера flexbox бесполезны, потому что элемент будет заблокирован , когда они станут элементами flex.

Включите перенос, и вы будете вести себя аналогично первому примеру:

div {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 200px;
  background: #f0f0f0;
}

span {
  display: inline-block;
  white-space: normal;
  vertical-align: top;
}

label {
  margin-top: 10px;
  /*white-space: nowrap;*/
}

.label1 {
  display: inline-block;
}

.label2 {
  display: flex;
  flex-wrap:wrap;
}
<div>

  <label class=label1>
 <input type=checkbox>
 <span>
  Here is a long description for the option that is set via the checkbox
  on the left. The label is set to inline-block. For some reason,
  it overflows the containing div. But why?
</span>
</label>

  <label class=label2>
 <input type=checkbox>
 <span>
  Here is a long description for the option that is set via the checkbox
  on the left. The label is set to flex. For some reason,
  it does not overflow the containing div. But why not?
</span>
</label>

</div>

Теперь добавьте обратно обрыв пробела:

div {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 200px;
  background: #f0f0f0;
}

span {
  display: inline-block;
  white-space: normal;
  vertical-align: top;
}

label {
  margin-top: 10px;
  white-space: nowrap;
}

.label1 {
  display: inline-block;
}

.label2 {
  display: flex;
  flex-wrap:wrap;
}
<div>

  <label class=label1>
 <input type=checkbox>
 <span>
  Here is a long description for the option that is set via the checkbox
  on the left. The label is set to inline-block. For some reason,
  it overflows the containing div. But why?
</span>
</label>

  <label class=label2>
 <input type=checkbox>
 <span>
  Here is a long description for the option that is set via the checkbox
  on the left. The label is set to flex. For some reason,
  it does not overflow the containing div. But why not?
</span>
</label>

</div>

С флексбоксом ничего не произойдет, потому что мы больше не имеем дело с текстом и встроенными элементами, но речь идет о флекс-элементах, поэтому пробелы там не действуют, так как ониявляются блочными элементами, и, как указано выше, обтекание контролируется flex-wrap.

Еще одна вещь, на которую следует обратить внимание, это то, что flex-элементы по умолчанию всегда сжимаются, чтобы соответствовать их родительскому контейнеру, что также объясняет, почемунет наложения, даже если вы установили явную ширину:

div {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 200px;
  background: #f0f0f0;
}

span {
  display: inline-block;
  white-space: normal;
  vertical-align: top;
}

label {
  margin-top: 10px;
  white-space: nowrap;
}

.label1 {
  display: inline-block;
}

.label2 {
  display: flex;
}
<div>

  <label class=label1>
 <input type=checkbox>
 <span>
  Here is a long description for the option that is set via the checkbox
  on the left. The label is set to inline-block. For some reason,
  it overflows the containing div. But why?
</span>
</label>

  <label class=label2>
 <input type=checkbox>
 <span style="width:200px;">
  Here is a long description for the option that is set via the checkbox
  on the left. The label is set to flex. For some reason,
  it does not overflow the containing div. But why not?
</span>
</label>

</div>

Но если вы отключите shrink, вы можете получить переполнение:

div {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 200px;
  background: #f0f0f0;
}

span {
  display: inline-block;
  white-space: normal;
  vertical-align: top;
}

label {
  margin-top: 10px;
  white-space: nowrap;
}

.label1 {
  display: inline-block;
}

.label2 {
  display: flex;
}
<div>

  <label class=label1>
 <input type=checkbox>
 <span>
  Here is a long description for the option that is set via the checkbox
  on the left. The label is set to inline-block. For some reason,
  it overflows the containing div. But why?
</span>
</label>

  <label class=label2>
 <input type=checkbox>
 <span style="width:200px;flex-shrink:0">
  Here is a long description for the option that is set via the checkbox
  on the left. The label is set to flex. For some reason,
  it does not overflow the containing div. But why not?
</span>
</label>

</div>

И без явной ширины у вас будет это:

div {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 200px;
  background: #f0f0f0;
}

span {
  display: inline-block;
  white-space: normal;
  vertical-align: top;
}

label {
  margin-top: 10px;
  white-space: nowrap;
}

.label1 {
  display: inline-block;
}

.label2 {
  display: flex;
}
<div>

  <label class=label1>
 <input type=checkbox>
 <span>
  Here is a long description for the option that is set via the checkbox
  on the left. The label is set to inline-block. For some reason,
  it overflows the containing div. But why?
</span>
</label>

  <label class=label2>
 <input type=checkbox>
 <span style="flex-shrink:0">
  Here is a long description for the option that is set via the checkbox
  on the left. The label is set to flex. For some reason,
  it does not overflow the containing div. But why not?
</span>
</label>

</div>

1 Вот еще один пример, иллюстрирующий эффект white-space:nowrap и то, как этого не делает изменить ширину элемента, рассчитанную ранее:

.box {
  width:200px;
  border:2px solid red;
}
.box span {
  border:2px solid green;
  white-space:normal;
  display:inline-block;
  vertical-align:top;
}
<div class="box">
  <span>lorem ipsume</span>
  <span> lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume</span>
  <span> lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume</span>
</div>

<div class="box" style="white-space:nowrap">
  <span>lorem ipsume</span>
  <span> lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume</span>
  <span> lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume lorem ipsume</span>
</div>
0 голосов
/ 20 февраля 2019

Вы обрабатываете span элементы с display: inline-block.По умолчанию элементы уровня блока составляют 100% ширины их родительского контейнера.Поскольку вы вводите вход и диапазон в одну строку с white-space: nowrap, это заставляет диапазон выходить за границы родительского контейнера.

Почему они имеют разную ширину?Почему один из них превышает свой контейнер, а другой - нет?

Использование display: flex позволяет дочерним элементам сжиматься в соответствии с доступным пространством, поэтому элемент span начинается с ширины родительского элемента 100%, но затемвместо этого сжимается, чтобы заполнить доступное пространство.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...