将Div调整大小以适应divs %

4

我的问题是我正在尝试制作一个响应式模板,现在我只在制作标题。

首先,我将在此处发布一些代码以让您了解。

<div id="header_box">
  <div class="box">
  Content of box / Img
  </div>
  <div class="box">
  Content of box / Img
  </div>
  <div class="box">
  Content of box / Img
  </div>
</div>

"header_box" 是100%宽度,而 "thinking box" 宽度约为40%。这意味着由于有3个 "box",它们的总宽度将达到120%。是否有一种方法可以自动调整 "box" 的宽度,例如调整为30%,如果再添加一个 "box",则调整为20%等等?谢谢。

2
你考虑过使用响应式框架,比如Bootstrap吗?它会为你节省不少麻烦。 - chris
你可以使用JavaScript来实现这个功能,它将允许你添加尽可能多的box div并适应header_box div。假设你最初有2个div,但之后你需要1个以上的div,那么你不需要改变宽度,它会动态设置并使总宽度为100%。如果你想,我可以发布解决方案。 - divy3993
@divy3993 当flexbox规范已经被广泛支持时,为什么要使用基于JS的解决方案呢? - Terry
2个回答

3

首先,你的ID应该是唯一的,所以在你给出的示例中,最好使用类(即class="box")。

你可以在CSS中使用flex和inline-flex来根据屏幕宽度调整DIV的大小。我在这里附上了一个基本示例:http://jsfiddle.net/18e3cxd1/

.box {
    display:inline-flex;
    width:30%;
    border:solid 1px red;
}

这个链接提供了关于使用弹性盒子布局的一些好的指导:https://css-tricks.com/snippets/css/a-guide-to-flexbox/


0

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}
.header_box{
    display: table;
    width: 100%;
    border-spacing: 5px;
}
.box{
    display: table-cell;
    vertical-align: top;
    padding: 15px;
    border: 1px solid #f00;
}

@media screen and (max-width: 400px) {
    
    .box{
        display: table-caption;
    }    
    
}
<div class="header_box">
    <div class="box">
        <p>Content of box / Img</p>
    </div>
    <div class="box">
        <p>Content of box / Img</p>
    </div>
     <div class="box">
        <p>Content of box / Img</p>
    </div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接