我是CSS的新手,我的头撞在墙上,试图弄清楚为什么当我有两个元素浮动在右边和一个左边时,第三个元素没有显示在中间。
#red {
width: 250px;
height: 250px;
background-color: red;
float:left;
}
#yellow {
width: 250px;
height:250px;
background-color: yellow;
float:right;
}
#blue {
width: 250px;
height:250x;
background-color:blue;
}
<p id="red">This is bullshit.</p>
<p id="yellow">It is taking me way to long to figure out.</p>
<p id="blue">WTF?</p>
我强烈建议使用flexx来解决这个问题。
.container {
display: flex;
justify-content: space-between;
}
#red { width: 250px; height: 250px; background-color: red; }
#yellow { width: 250px; height:250px; background-color: yellow; }
#blue { width: 250px; height:250x; background-color:blue; }
<div class="container">
<p id="red">This is bullshit.</p>
<p id="yellow">It is taking me way to long to figure out.</p>
<p id="blue">WTF?</p>
</div>
我还建议您使用Flex Box属性(Flexbox指南)),虽然如果你想用三种方式来修复它,这里是你的解决方案:
首先你必须明白,默认情况下p
标签是显示块属性,所以你必须把它作为内联块,像span
标签,并使溢出隐藏,所以它不会占用任何额外的空间。
#red,#yellow,#blue{
display: inline-block;
overflow: hidden;
}
#red {
width: 150px;
height: 150px;
background-color: red;
float: left;
}
#yellow {
width: 150px;
height:150px;
background-color: yellow;
}
#blue {
width: 150px;
height:150px;
background-color: blue;
}
<p id="red">This is bullshit.</p>
<p id="yellow">It is taking me way to long to figure out.</p>
<p id="blue">WTF?</p>
出现这个问题是因为第三个元素是一个p元素,默认情况下它不是内联元素。
看到MDN
float CSS属性将元素放置在的左侧或右侧它的容器,允许文本和内联元素环绕它。
尝试将蓝色设置为:inline,你会看到不同。
如果你真的需要红色和黄色浮动,也就是说,蓝色的东西在中间,然后缠绕,那么显然坚持浮动。如果不需要,那么研究flex或grid。