Having the floating children elements determine parent width

前端 未结 4 1551
春和景丽
春和景丽 2020-12-19 17:44

Here is an example

http://jsfiddle.net/BringMeAnother/LwXhE/

// html
相关标签:
4条回答
  • 2020-12-19 17:53

    Besides Adsy suggestion (to set the container's position to fixed), you could:

    1) Use position absolute on the container:

    HTML:

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

    CSS:

    .container {
        background: red;
        padding: 10px;
        position:absolute;
    }
    .child {
        width: 100px;
        height: 100px;
        float: left;
    }
    .child:nth-child(even) {
        background: green;
    }
    .child:nth-child(odd) {
        background: blue;
    }
    

    http://jsfiddle.net/tKz8b/

    2) Set a float on the container, which is good if you need it with relative / static positioning:

    HTML:

    <div class="container">
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
    </div>
    <div class="clearfix"></div>
    <div>Next</div>
    

    CSS:

    .container {
        background: red;
        padding: 10px;
        float: left;
    }
    .child {
        width: 100px;
        height: 100px;
        float: left;
    }
    .child:nth-child(even) {
        background: green;
    }
    .child:nth-child(odd) {
        background: blue;
    }
    
    .clearfix:after {
        content: ".";
        display: block;
        clear: both;
        visibility: hidden;
        line-height: 0;
        height: 0;
    }
    

    http://jsfiddle.net/LYrWx/1/

    0 讨论(0)
  • 2020-12-19 17:57

    Late to the party here, but all you really need is to add display: inline-block. And to center the .container div, just apply text-align: center to whatever contains it.

    JSFiddle: http://jsfiddle.net/LwXhE/24/

    0 讨论(0)
  • 2020-12-19 18:07

    By wrapping your container div in another wrapper div, you can centre your red container div, and the red div will only be as wide as its floating children.

    HTML

    <div class="centered">
        <div class="container">
            <div class="child"></div>
            <div class="child"></div>
            <div class="child"></div>
        </div>
    </div>
    

    CSS

    .centered {
        text-align: center;
    }
    .container {
        background: red;
        padding: 10px;
        display: inline-block;
    }
    .child {
        width: 100px;
        height: 100px;
        float: left;
    }
    .child:nth-child(even) {
        background: green;
    }
    .child:nth-child(odd) {
        background: blue;
    }
    

    Fiddle: http://jsfiddle.net/SbPRg/

    0 讨论(0)
  • 2020-12-19 18:18

    Add position:fixed; to container

    .container {
        background: red;
        padding: 10px;
        position:fixed;
    

    Fiddle

    0 讨论(0)
提交回复
热议问题