一旦元素突破父母的宽度,元素就会丢失所有宽度

Pri*_*Nom 6 html css html5 css3

为什么以下示例中的元素会自行折叠?

即使元素设置为box-sizing: border-box,它的边框也会保留,但是一旦元素突破其父级的边界,该元素就会丢失其全部宽度.

到底是怎么回事?

CODEPEN

let   t = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus at velit commodo, facilisis ex vitae, viverra tellus.'
let   c = 0
const e = document.getElementById('statement-container')
const i = setInterval(function(){
  if (t[c] !== ' ') e.innerHTML += t[c]
  else e.innerHTML += ' '
  c++
  if (c >= t.length) clearInterval(i)
}, 100)
Run Code Online (Sandbox Code Playgroud)
* {
  box-sizing : border-box;
}

body {
  width       : 100vw;
  height      : 100vh;
  margin      : 0;
}

section:first-child {
  width       : 40vw;
  height      : 100vh;
  position    : relative;
  left        : 30vw;
  display     : flex;
  border      : solid blue 1px;
}

#statement-container, #caret {
  height      : 15%;
  position    : relative;
  top         : calc(50% - 7.5%);
}

#statement-container {
  z-index     : 98;
  font-family : beir-bold;
  font-size   : 6.5vmin;
  color       : red;
}

#caret {
  z-index     : 99;
  width       : 10%;
  border      : solid green 5px;
  background  : orange;
}
Run Code Online (Sandbox Code Playgroud)
<body>
  <section>
    <div id="statement-container"></div>
    <div id="caret"></div>
  </section>
</body>
Run Code Online (Sandbox Code Playgroud)

LGS*_*Son 5

为什么以下示例中的元素会自行折叠?

当你正在使用display: flexsection,它的孩子变得弯曲的物品.

Flex项目有一个名为的属性flex,它是简历flex-grow,flex-shrinkflex-basis根据可用空间及其内容控制项目大小本身的方式.

flex-basis,在这种情况下,一个柔性行方向,这是缺省值,控制所述项的宽度.

默认值是flex: 0 1 auto指不会超出其内容的增长(0),允许收缩(1)及其flex-basis(auto)根据其内容调整大小.

因为在这种情况下width并且flex-basis做同样的,这里给出caret3%的设定宽度,只要有足够的空间就会保持宽度,并且不会增长,但是当空间变为负数时(物品将不适合)它将开始缩小到其内容宽度,它没有任何内容宽度,因此其内容区域完全崩溃.


一种解决方案是通过改变flex-shrink来告诉它不被缩小0.

let   t = 'Nothing is completely perfect.'
let   c = 0
const e = document.getElementById('statement-container')
const i = setInterval(function(){
  if (t[c] !== ' ') e.innerHTML += t[c]
  else e.innerHTML += '&nbsp;'
  c++
  if (c >= t.length) clearInterval(i)
}, 100)
Run Code Online (Sandbox Code Playgroud)
* {
  box-sizing : border-box;
}

body {
  width  : 100vw;
  height : 100vh;
  margin : 0;
}

section:first-child {
  width    : 40vw;
  height   : 100vh;
  position : relative;
  left     : 30vw;
  display  : flex;
  border   : solid blue 1px;
}

#statement-container, #caret {
  height      : 15%;
  position    : relative;
  top         : calc(50% - 7.5%);
}

#statement-container {
  font-family : beir-bold;
  font-size   : 15vmin;
  color       : red;
}

#caret {
  flex-shrink : 0;                             /* added  */
  width       : 5%;
  border      : solid green 5px;
  background  : orange;
}
Run Code Online (Sandbox Code Playgroud)
  <section>
    <div id="statement-container"></div>
    <div id="caret"></div>
  </section>
Run Code Online (Sandbox Code Playgroud)