side by side divs

后端 未结 7 2132
忘掉有多难
忘掉有多难 2020-12-19 01:25

I\'ve got 4 divs inside a parent div. To get them to appear side by side, I\'ve given all 4 divs a style with float:left. The divs do appear side by side, but the parent d

相关标签:
7条回答
  • 2020-12-19 02:04

    After the 4 divs, you need to "cancel" the float style. This is done through the creation of a p for example, like: <p style="clear: both"></p> Your parent div will automatically get the right size.

    0 讨论(0)
  • 2020-12-19 02:06

    I recommend the clearfix method as well. This problem occurs because floating an element removes any height that it would normally contain.

    PositionIsEverything posts a complete explanation as well as corresponding solutions for IE6, since the :after pseudoselector is not supported by older browsers.

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

    I think you should give the parent div a height of 100% not fixed so that it encompasses the height of child divs if they grow.

    0 讨论(0)
  • 2020-12-19 02:10

    Set overflow: hidden; on the parent div.

    Explanation: floating elements removes them from the regular document flow. So, if a given element contains only floated elements, it will not have any height (or, by extension, width -- unless it has an implicit width that is default on block elements).

    Setting the overflow property to hidden tells the parent element to respect the width of it's children, but hide everything that falls outside it's width and height.

    Of course, the other option is to add an element after the floated divs, inside the parent, with clear: both; This makes the last element be positioned after all the floats, within the regular document flow. Since it's inside the parent, the parent's height is whatever the heights of the floated items are, plus regular padding and the height of the cleared item.

    0 讨论(0)
  • 2020-12-19 02:11

    millinet's answer will work, or you could float the parent div which will also allow it to expand to contain its content

    0 讨论(0)
  • 2020-12-19 02:15

    If you want the divs to be side-by-side, you could try using inline-block:

    <style>
        .alldivs {
            display: inline-block;
        }
    </style>
    
    <div id="wrapper">
        <div id="div1" class="alldivs"></div>
        <div id="div2" class="alldivs"></div>
        <div id="div3" class="alldivs"></div>
        <div id="div4" class="alldivs"></div>
    </div>
    
    0 讨论(0)
提交回复
热议问题