我有这段代码
.outer {
background-color: #ff00ff;
width: 100%;
}
.outer div {
float: left;
background-color: #0000ff;
}
<div class="outer">
<div>
test1 <br/> test1
</div>
<div>
test2 <br/> test2
</div>
</div>
https://jsfiddle.net/jcb5mdqa/
看起来像是
但我希望外部的宽度为100%,就像写入.css一样。
预期结果
我需要改变什么?
答案 0 :(得分:2)
.outer
已经宽度为100%,因为它是一个块元素。它缺乏高度,因为内容是浮动的。要为.outer
提供内容的高度,请将overflow: auto
添加到类定义中:
.outer {
background-color: #ff00ff;
overflow: auto;
}
.outer div {
float: left;
background-color: #0000ff;
}
&#13;
<div class="outer">
<div>
test1 <br/> test1
</div>
<div>
test2 <br/> test2
</div>
</div>
&#13;
答案 1 :(得分:1)
使用clearfix
.outer {
background-color: #ff00ff;
width: 100%;
}
.outer div {
float: left;
background-color: #0000ff;
}
.clearfix:after {
content: "";
display: table;
clear: both;
}
&#13;
<div class="outer clearfix">
<div>
test1 <br/> test1
</div>
<div>
test2 <br/> test2
</div>
</div>
&#13;
答案 2 :(得分:1)
解决这个问题有两个方面:
.outer {
background-color: #ff00ff;
width: 100%;
}
.outer:after {
display: block;
content: "";
clear: both;
}
.outer div {
float: left;
background-color: #0000ff;
}
<div class="outer">
<div>
test1
<br/> test1
<br/> test1
</div>
<div>
test2
<br/> test2
<br/> test2
</div>
</div>
浮动,绝对定位的元素,阻止不是块框的容器(例如内联块,表格单元格和表格标题),以及除“可见”以外的“溢出”的块框(除非该值已传播到视口)为其内容建立新的块格式化上下文。
.outer {
background-color: #ff00ff;
width: 100%;
/* float and below overflow peoperties can both establish a new BFC */
// float: left;
overflow: auto;
}
.outer div {
float: left;
background-color: #0000ff;
}
<div class="outer">
<div>
test1
<br/> test1
<br/> test1
</div>
<div>
test2
<br/> test2
<br/> test2
</div>
</div>
答案 3 :(得分:0)
使用overflow:auto
.outer {
background-color: #ff00ff;
width: 100%;
overflow:auto;
}
.outer div {
float: left;
background-color: #0000ff;
}
<div class="outer">
<div>
test1 <br/> test1
</div>
<div>
test2 <br/> test2
</div>
</div>
答案 4 :(得分:0)
方法1:使用
<br style="clear: both">
.outer {
background-color: #ff00ff;
width: 100%;
}
.outer div {
float: left;
background-color: #0000ff;
}
<div class="outer">
<div>
test1 <br/> test1
</div>
<div>
test2 <br/> test2
</div>
<br style="clear: both">
</div>
方法2:使用
overflow:hidden
.outer {
background-color: #ff00ff;
width: 100%;
overflow: hidden;/*/<=========new/*/
}
Mehod 3:使用
:after
.outer:after {
content: '';
clear: both;
display: block;
}