简体   繁体   English

左浮动div的中心容器

[英]Center container of left floated divs

Although a lot of questions are about similar issues, they always want all items centered (which of course can be done using display:inline-block ), however I need the last line of items to be neatly floated left and only center the container (which is located in a variable container (the body) itself). 虽然很多问题都是关于类似的问题,但是他们总是希望所有项目都集中在一起(当然可以使用display:inline-block来完成),但是我需要将最后一行项目整齐地漂浮在左边并且只将容器放在中心位置(它位于一个可变容器(主体)本身)。

漂浮的div

The problem is that no matter what display and clear I set for the container, it never takes the width of the containing floated elements. 问题是,无论我为容器设置什么displayclear ,它都不会占用包含浮动元素的宽度。 I am seriously tempted to think that this should be incredibly simple, but I can't figure out how to get it working. 我很想认为这应该非常简单,但我无法弄清楚如何让它发挥作用。

Here is a basic fiddle to play around with. 这是一个可以玩的基本小提琴

You have to use an inner div for your solution: 你必须为你的解决方案使用内部div:

CSS: CSS:

#inner{
    width:396px; /* (100+15*2+2) * 3 */
    margin:auto;
}

HMTL: HMTL:

<div id="container">
    <div id="inner">
        <div class="block">1</div>
        <div class="block">2</div>
         <div class="block">3</div>
         <div class="block">4</div>
         <div class="block">5</div>
         <div class="clear"></div>
    </div>
</div>​

DEMO and DEMO without fixed body width. DEMODEMO没有固定的车身宽度。

UPD: just noticed that you don't want your body width to be fixed. UPD:刚注意到你不希望你的体宽被修复。 Use width:80%; 使用width:80%; then instead. 然后改为。 DEMO DEMO

The problem is you need 2 divs to center this correctly then a set width div to contain all the blocks. 问题是你需要2个div来正确居中,然后设置一个宽度div以包含所有块。 Then you can clear it and use the inner inner div (called 'content' in my code here) to control the beginning of the inner float. 然后你可以清除它并使用内部内部div(在我的代码中称为“content”)来控制内部浮动的开始。

Updated your fiddle: http://jsfiddle.net/h9H8w/8/ 更新了你的小提琴: http//jsfiddle.net/h9H8w/8/

// HTML
<div id="container">
    <div id="inner">
         <div id="content">
             <div class="block">1</div>
             <div class="block">2</div>
             <div class="block">3</div>
             <div class="block">4</div>
             <div class="block">5</div>
        </div>
    </div>
</div>​

// CSS
body{
    width: 100%;
}
#container{
    float: left;
    position: relative; 
    left: 50%;
}
#inner{
    float: left;
    position: relative; 
    left: -50%;
    border:1px solid black;
}
#content{width: 500px;}
.clear{
    clear:both;
}
.block{
    float: left;
    width:100px;
    height:50px;
    border:1px solid black;
    margin: 15px;

}​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM