1

我有一个名为的外部 div 元素和两个名为和的container内部 div 元素firstDivsecondDiv

firstDiv 将浮动到左侧,而 secondDiv 将浮动到右侧。

我希望外部 div 元素尽可能多地占用宽度,这意味着 100% 的可用宽度。

我还希望两个内部元素占用一半空间,这意味着containerdiv 的 50%。

这是一些基本代码:

<html>
    <head>
    
    <style type="text/css">
        #container{
            width:100%;
            height:100%;
            border-style:solid;
        }
    </style>
    </head>
    
    <body>
        <div id="container">
            <div id="firstDiv"> </div>
            <div id="secondDiv"> </div>
        </div>
    </body>
</html>

问题 1

我期待一个简单的实体边框围绕 body 元素,看起来确实如此,但是我在浏览器的 y 维度上有一个滚动条。为什么会这样?我说我想要 100% 的 body 宽度和高度,看起来浏览器使用的不止这些。

现在我添加了以下 CSS 代码:

    #firstDiv{
        width:50%;
        height:100%;
        border-style:solid;
        }

问题 2 似乎 div 占据了“容器”div 的 50%,但高度似乎超过了 100%。为什么会这样?图片: enter image description here

我对第二个 div 执行相同的操作,并通过使用以下 CSS 代码来包含 float 属性:

    #container{
        width:100%;
        height:100%;
        border-style:solid;
    }
    #firstDiv{
        width:50%;
        height:100%;
        border-style:solid;
        float:left;
        }
    #secondDiv{
        width:45%;
        height:100%;
        border-style:solid;
        float:right;
        }

问题 3 我希望两个 div 元素组成一个两列页面。然而,第二个 div 元素再次比前一个元素占用更多的高度,而且发生的情况是当我调整浏览器大小时,第二个 div 位于第一个下方。

enter image description here

为什么会发生这种情况,我该如何避免?

提前致谢

4

2 回答 2

3

All your questions are due to the box-model you misunderstood. height: 100% makes the content-height 100%. When you have a border AND height: 100% this leads to 100% + border-width, which obviously is more than 100%.

A possible solution is to use box-sizing: border-box;

The only browser not supporting this property are IE<8. If these are relevant to you, you could create a workaround with CSS-expressions for them. Handle with care!

于 2012-11-29T13:42:18.193 回答
2

Borders are not counted when calculating the width of an element. They are supplements to the specified width. This explains your slight inconsistencies. There is no 100% airtight solution to this problem as far as I know that will do exactly what you want (close to it, yes, but exactly, no). The most reliable is to use a table, but that isn't a valid solution for designing a page layout as you already certainly know. Another option is to float right and left but have the width specified as either a slightly lower percentage than 50 (such as 48-48) or have a width specified in px which would allow you to calculate precisely the exact sizes that you need.

When browsers begin to uniformly implement CSS3, the box-sizing property will be able to solve this problem. box-sizing specifies what to take into account when calculating the size of an element. Applying box-sizing:border-box; will take the border into account, but for the moment this isn't widely enough implemented across browsers to use reliably in your code.

于 2012-11-29T13:43:04.603 回答