CSS居中并排

时间:2012-07-09 18:01:39

标签: html css

我的页面有以下部分。
式:

.featuredcontainer {

width: 450px;
height: 700px;
margin-left: auto;
margin-right: auto;
position: relative;
right: 160px;
top: 30px;
border: 1px groove grey;
}



.navcontainer
{
margin-left: auto;
margin-right: -8px;
position: relative;
top: 75px;
height: 600px;
width: 300px;
}

示例HTML:

<div class="featuredcontainer">
content
</div>
<div class="lessonnavcontainer">
menu
</div>

显示页面时。 navcontainer位于(应该)的右边,但在特色容器下面。当我使用相对定位向上移动navcontainer时,它看起来是正确的,但页面底部有一堆空的空间。我该怎么办?

5 个答案:

答案 0 :(得分:1)

将nav和特色容器放入另一个包装器div。

<强> HTML

<div class='wrapper'>
    <div class="navcontainer">
        menu
    </div>
    <div class="featuredcontainer">
        content
    </div>
</div>

摆脱所有的相对定位。对于像这样的基本布局问题,不建议使用相对定位。请改用浮子。包装器应该有一个固定的宽度,这使得它可以正确居中,边距为:0 auto。

<强> CSS

.wrapper{
    width:752px;
    margin: 0 auto;
    overflow:auto;
}
.featuredcontainer {
    width: 450px;
    height: 700px;
    float:left;
    border: 1px groove grey;
}
.navcontainer{
    float:left;
    height: 600px;
    width: 300px;
    background:#ff0;
}

JSFiddle http://jsfiddle.net/5w5SC/

答案 1 :(得分:0)

使用 float 属性。使用float,css可以将divs水平放置在彼此旁边。

.featuredcontainer {

width: 450px;
height: 700px;
margin-left: auto;
margin-right: auto;
position: relative;
right: 160px;
top: 30px;
border: 1px groove grey;
float: left;
}



.navcontainer
{
margin-left: auto;
margin-right: -8px;
position: relative;
top: 75px;
height: 600px;
width: 300px;
float: left;
}

这是一个起点,尝试使用向左浮动或向右浮动,看看会发生什么。摆弄它,直到它看起来你想要它。

答案 2 :(得分:0)

要并排获取它们,您需要在CSS中添加float属性。要让它们使用页面宽度调整大小,您需要为它们添加相对宽度。要将它们居中在页面上(水平),您需要将div放在html中相对定位的div内。这是一个小提琴。 http://jsfiddle.net/Ne5zs/

答案 3 :(得分:0)

使用“wrapper”div围绕你的两个div:

<div id="wrapper">
    <div class="featuredcontainer">content</div>
    <div class="lessonnavcontainer">menu</div>
</div>

然后将它们居中,为包装器添加边距:

#wrapper { margin: 0px auto; }

然后让两个div并排,添加一个浮点数:

.featuredcontainer { float: left; }
.lessonavcontainer { float: left; }

为了使居中工作,你需要在包装器上声明一个宽度:

#wrapper { width: 800px; }

答案 4 :(得分:0)

请务必在任何浮动对象上引入clearfix(there are many versions of this technique);然后使用margin: 0 auto将其包含块元素居中。