在 div 内平均分配 3 div - 没有浮动
Equally distribute 3 divs within a div - without float
我已经广泛阅读了这方面的资料,但一直未能满意地解决它。
我有一个 div (<section>
),其中包含一个 <p>
和 3 个 <div>
。我想在一行中平均分配 3 个 div,以便第一个 div 的左边框位于文档的左边框(<body>
)和右边框第 3 个 div 在文档的右边框上。
我不想使用浮动,因为背景色会消失。
我试过 flex,但 justify-content
没有产生预期的结果。
这是 JSBIN 上的代码。
谢谢!
您可以在容器上使用 display: flex
,并将三个 div 元素的宽度设置为占据其容器的三分之一(或尽可能接近)。容器必须具有设置的宽度(像素或百分比)才能正常工作。
#container {
display: flex;
height: 600px;
width: 600px;
background-color: lightgreen;
}
#container div {
border: 1px solid black;
margin: 0 10px;
width: 33.333333%;
}
#container div img {
width: 100%;
}
<div id="container">
<div id="content1">
I'm some content. Regardless of the width of this div, the content will move to the next line and stay within the div instead of overflowing.
<img src="http://i.imgur.com/P8z2H80.jpg">
</div>
<div id="content2">
I'm some more content. Regardless of the width of this div, the content will move to the next line and stay within the div instead of overflowing.
<img src="http://i.imgur.com/NfnBZAI.jpg">
</div>
<div id="content3">
I'm even more content. Regardless of the width of this div, the content will move to the next line and stay within the div instead of overflowing.
<img src="http://i.imgur.com/W8M37N2.jpg">
</div>
</div>
我已经广泛阅读了这方面的资料,但一直未能满意地解决它。
我有一个 div (<section>
),其中包含一个 <p>
和 3 个 <div>
。我想在一行中平均分配 3 个 div,以便第一个 div 的左边框位于文档的左边框(<body>
)和右边框第 3 个 div 在文档的右边框上。
我不想使用浮动,因为背景色会消失。
我试过 flex,但 justify-content
没有产生预期的结果。
这是 JSBIN 上的代码。
谢谢!
您可以在容器上使用 display: flex
,并将三个 div 元素的宽度设置为占据其容器的三分之一(或尽可能接近)。容器必须具有设置的宽度(像素或百分比)才能正常工作。
#container {
display: flex;
height: 600px;
width: 600px;
background-color: lightgreen;
}
#container div {
border: 1px solid black;
margin: 0 10px;
width: 33.333333%;
}
#container div img {
width: 100%;
}
<div id="container">
<div id="content1">
I'm some content. Regardless of the width of this div, the content will move to the next line and stay within the div instead of overflowing.
<img src="http://i.imgur.com/P8z2H80.jpg">
</div>
<div id="content2">
I'm some more content. Regardless of the width of this div, the content will move to the next line and stay within the div instead of overflowing.
<img src="http://i.imgur.com/NfnBZAI.jpg">
</div>
<div id="content3">
I'm even more content. Regardless of the width of this div, the content will move to the next line and stay within the div instead of overflowing.
<img src="http://i.imgur.com/W8M37N2.jpg">
</div>
</div>