元素互相进入

时间:2013-12-10 20:45:42

标签: css css-float margin

我正在开发一个简单的css主题,我正在使用左中右侧布局,我使用float来定位右侧和左侧元素,使用margin作为中心。 但是,如果我看一下网站,所有的网站部分都会互相进入。

这是我现在所拥有的:

HTML

<div class="container">
    <div class="right">
        <div class="block">
            <div class="title">My Block Of Data Here Is Title</div>
            This is my block of data! Here i can show website stats and announcements.
        </div>
    </div>
    <div class="left">
        <div class="block">
            <div class="title">My Block Of Data Here Is Title</div>
            This is my block of data! Here i can show website stats and announcements.
        </div>
    </div>
    <div class="center">                
        <div class="block">
            <div class="title">Welcome to SITE_TITLE_HERE!</div>
            This is where we post so many stuff!<br><br><br><br><br><br><br><br><br><br>Thanks, SITE_TITLE_HERE stuff.
        </div>
    </div>
</div>

CSS

body{
    font-family: 'Open Sans Condensed', sans-serif;
    font-size: 18px;
}

.container{
    margin: 0 auto;
    width: 65%;
}   

.left{
    float: left;
    width: 20%;
}   

.right{
    float: right;
    width: 20%;
}

.center{
    margin: 0 auto;
    width: 60%;
}

.block{
    width: 100%;
    padding: 3px;
    background: #fafafa;
    outline: 1px solid #f2f2f2;
    outline-offset: 2px;
    text-align: center;
}

.block .title{
    font-size: 24px;
    border-bottom: 1px solid #000;
    background: #76E0EE;
}

小提琴: http://jsfiddle.net/XK6dN/2/

更新:我几乎可以肯定它是块类的outline,但即使它就是这样。我如何防止他们互相压倒?

2 个答案:

答案 0 :(得分:3)

这只是因为元素的宽度没有加起来。

填充/边框以元素的宽度计算,因此:

20% + 20% + 60% + 6px(填充)+ 2px(边框)!= {{1 }}

您可以使用属性box-sizing更改元素的框模型,以在其宽度计算中包含填充/边框。

jsFiddle example

100%

但仍然存在一个问题,因为每个元素的每一方都有.block{ box-sizing: border-box; -moz-box-sizing: border-box; } outline

我建议将其更改为1px,从而解决问题。

或者,您可以使用box-sizing从元素宽度中减去填充/边框,而不是使用calc()

jsFiddle example

border

答案 1 :(得分:1)

这是因为对于每个浮动div的子.block个元素以及居中的div,您声明100%宽度(因此继承父级的宽度)另外一个宽度为6px(左右填充3px)。这会导致内容溢出,因为您在100%宽度之上添加了6px。

要解决此问题,请在box-sizing: border-box上声明.block

.block {
    box-sizing: border-box; /* Makes magic happen */
    width: 100%;
    padding: 3px;
    background: #fafafa;
    outline: 1px solid #f2f2f2;
    outline-offset: 2px;
    text-align: center;
}

这不是魔法本身,但是使用border-box box model,你强迫100%宽度包括所有可能的装饰,包括轮廓,边框和填充,是在计算最终宽度时考虑到了。

http://jsfiddle.net/XK6dN/3/

相关问题