Why is an element with width:100% not taking the parent's width?

笑着哭i 提交于 2019-12-30 10:43:51

问题


I am facing the issue that I cannot set the same width as its parent inside a flexbox item.

Here is the code and the span with the class theSpan doesn't have the same width as its parent.

.container {
  display: flex;
}
.item1 {
  flex: 1 1 200px;
  border: 5px solid yellow;
}
.item2 {
  flex: 1 1 200px;
  border: 5px solid blue;
}
.item3 {
  flex: 1 1 200px;
  border: 5px solid red;
}
.theSpan {
  width: 100%;
  border: 2px solid black;
}
<div class='container'>
  <div class='item1'>
    <span class='theSpan'>abcdefg</span>
  </div>
  <div class='item2'>
    <span>1</span>
  </div>
  <div class='item3'>
    <span>2</span>
  </div>
</div>

回答1:


Your span element with class theSpan is a child of a flex item (.item1).

This flex item is not a flex container.

Because only the children of a flex container participate in flex layout, the span (a grandchild) is disqualified. It does not exist in a flex formatting context.

The span exists in a standard block formatting context.

In a BFC, a span is, by default, an inline, non-replaced element.

The reason width: 100% does not work is provided in the spec:

10.2 Content width: the width property

This property does not apply to non-replaced inline elements. The content width of a non-replaced inline element's boxes is that of the rendered content within them.

10.3.1 Inline, non-replaced elements

The width property does not apply.




回答2:


You should turn the span into block via display.

.container {
  display: flex;
}
.item1 {
  flex: 1 1 200px;
  border: 5px solid yellow;
}
.item2 {
  flex: 1 1 200px;
  border: 5px solid blue;
}
.item3 {
  flex: 1 1 200px;
  border: 5px solid red;
}
.theSpan {
  display:block;/* <= display instead or with width will do */
  border: 2px solid black;
}
<div class='container'>
  <div class='item1'>
    <span class='theSpan'>abcdefg</span>
  </div>
  <div class='item2'>
    <span>1</span>
  </div>
  <div class='item3'>
    <span>2</span>
  </div>
</div>



回答3:


make .item1 a display:flex as well then set the .theSpan as flex:1 and you can set all the items as flex:0 200px since you want to have a flex-basis of 200px you don't need to have flex:1

.container {
  display: flex;
}
.container > div {
  flex: 0 200px
}
.item1 {
  display: flex;
  border: 5px solid yellow;
}
.item2 {
  border: 5px solid blue;
}
.item3 {
  border: 5px solid red;
}
.theSpan {
  flex: 1;
  border: 2px solid black;
}
<div class='container'>
  <div class='item1'>
    <span class='theSpan'>abcdefg</span>
  </div>
  <div class='item2'>
    <span>1</span>
  </div>
  <div class='item3'>
    <span>2</span>
  </div>
</div>


来源:https://stackoverflow.com/questions/39577892/why-is-an-element-with-width100-not-taking-the-parents-width

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!