我有一个包含多个 float 元素的容器 div。我正在尝试使容器宽度适合内容。我现在有一个最初使容器适合内容的 jsFiddle:
但是,一旦屏幕宽度变小,内容div没有空间显示在同一行,就会出现这种情况:
这是我的代码:
.container {
border: 1px solid red;
display: table;
}
.content {
border: 1px solid blue;
width: 100px;
height: 100px;
float: left;
}
<div class="container">
<div class="content"></div>
<div class="content"></div>
<div class="content"></div>
<div style="clear:both"></div>
</div>
应该发生的是,当第三个内容 div 进入下一行时,容器 div 应该变小以适应内容。我怎样才能使容器宽度适合所有情况下的内容?
编辑澄清:
子 div 的行为正确。这道题只是关于改变容器的宽度。
您可以使用媒体查询根据屏幕大小更改容器宽度。 .container
在正常情况下取 width
等于子 width
,每个子取 width: 102px
(width + border左/右) , .container
width
= children width + container border;
当屏幕宽度小于 .container
宽度时,它会将最后一个元素推到下面。从这一点开始,您可以根据 .container 宽度设置媒体查询。
https://jsfiddle.net/v5czL9he/2/
* {
margin:0;
padding: 0;
}
.container {
border: 1px solid red;
display: table;
}
.content {
border: 1px solid blue;
width: 100px;
height: 100px;
float: left;
}
/* if screen width < .container width
decrease last element from fisrt row
decrease it's width from the container width
*/
@media only screen and ( max-width: 308px ) {
.container {
width: calc( 306px - 102px );
}
}
@media only screen and ( max-width: 206px ) {
.container {
width: calc( 204px - 102px );
}
}
<div class="container">
<div class="content"></div>
<div class="content"></div>
<div class="content"></div>
<div style="clear:both"></div>
</div>