将div宽度调整为浮动内容

时间:2016-06-18 13:51:41

标签: html css css-float

我有一个容器div,里面有多个浮动元素。我试图使容器宽度适合内容。我现在有一个最初适合容器的jsFiddle:

Correct fit

但是,只要屏幕宽度变小并且内容div没有空间显示在同一行上,就会发生这种情况:

Wrong fit

这是我的代码:

.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>
应该发生的是当第3个内容div进入下一行时,容器div应该变小以适应内容。如何在所有情况下使容器宽度适合内容?

编辑以澄清: child-div表现正常。这个问题只是关于改变容器的宽度。

2 个答案:

答案 0 :(得分:1)

您可以使用媒体查询根据屏幕大小更改容器宽度。正常的.container需要width等于孩子width,每个孩子需要width: 102px(宽度+边框左/右),.container width =儿童宽度+容器边界;

当屏幕宽度小于.container宽度时,它将推送下面的最后一个元素。从这一点开始,您可以根据.container width设置媒体查询。

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>

答案 1 :(得分:0)

添加固定宽度? (如果我理解你想要的话)

width:305px;
相关问题