开发者

CSS 3 columns, why is the third column taking over the other 2?

开发者 https://www.devze.com 2022-12-25 04:01 出处:网络
Here is the smallest amount of code that c开发者_Python百科learly illustrates my problem: <html>

Here is the smallest amount of code that c开发者_Python百科learly illustrates my problem:

<html>
<body>
    <div style="float: left; width: 200px;">One</div>
    <div style="float: left; width: 200px;">Two</div>
    <div style="background-color: #f0f;">Three</div>
</body>
</html>

The first 2 divs are supposed to be 2 left columns. The 3rd should take up the rest of the page. Eventually, I'm going to add options to hide and show the 2 columns on the left.

But, why is the color purple extending all the way to the browser's left edge? I am trying to get it to start at the word "Three".


You need to 'float' the third column as well. Then add a clearing block after it.


See Block formatting contexts by W3C:

In a block formatting context, each box's left outer edge touches the left edge of the containing block (for right-to-left formatting, right edges touch). This is true even in the presence of floats (although a box's line boxes may shrink due to the floats), unless the box establishes a new block formatting context (in which case the box itself may become narrower due to the floats).

You can avoid that by forcing creation of new blocking formatting context:

<div style="background-color: #f0f; overflow: hidden">Three</div>

If overflow: hidden is not an option for you (popups etc.), here is another technique:

<div class="has-columns">
    <div class="column first">...</div>
    <div class="column second">...</div>
    <div class="column third">...</div>
</div>


.has-columns {
    padding-left: 400px; /* padding reserved for floats */
}

.column.first {
    width: 180px;
    margin-left: -400px;
    float: left;
}

.column.second {
    width: 180px;
    margin-left: -200px;
    float: left;
}

I have to admit, the behavior of floats can be confusing sometimes.


Depending what you want to have happen when columns one and two disappear, you have a few options:

1) If you want column 3 to expand and fill all the remaining space simply add overflow: hidden; to the styles of the third div. It will flow next to the two floated divs just as you expect.

2) If you want the third column to keep it's size and shape no matter what happens to columns 1 and 2, float it to the right, with a set width such as float: right; width: 200px; and it will no longer be effected by the other two, but stay 200px at the right edge of the container.

0

精彩评论

暂无评论...
验证码 换一张
取 消