Frage

I guess this may have been asked a lot of times, but I've searched accross the forum and haven't find the answer for this case.

I've some divs "container" and some divs "item" all of them floated elements, and I want each "container" below the previous one.

I know I could achieve that without using floats on the containers. But I thought that using :after and clear: would be enough.

Why this doesn't work?

My code:

<!doctype html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="./style2.css">
</head>
<body>
    <header></header>

    <div class="container">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </div>

    <div class="container">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </div>

    <div class="container">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </div>

</body>
</html>

My CSS:

* {
    margin: 0;
    padding: 0;
}

header {

    width: 100%;
    min-height: 25px;
    background-color: #444;
    position: fixed;
    overflow: auto;
}

.container {
    float: left;
    padding: 10px;
    margin: 10px;
}

.container:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

.item {
    min-width: 50px;
    min-height: 50px;
    float: left;
    background-color: lightblue;
    border: 1px solid red;
    margin: 5px;
}

Thank you

War es hilfreich?

Lösung

Just add clear:left to your .container rules

.container {
    clear:left;
    float: left;
    padding: 10px;
    margin: 10px;
}

jsFiddle example

Andere Tipps

You can use the clearfix approach by adding the .clearfix class to your .container divs:

.clearfix:before,

.clearfix:after{
    content: " ";
    display: table;
}

.clearfix:after{
    clear: both;
}

<div class="container clearfix">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>

With this approach, you don't need to float: left your .container, and also, Clearfix it's going to help you each time a div has floated children by making it's height variable according to its children.

Another approach would be adding clear: left to your .container but I don't recommended it since it would be an specific approach solution.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top