在页面中心对齐很多div,有更简单的方法吗?

时间:2012-10-18 14:38:15

标签: html css

我的代码如下:

<div id="divone"><div class="content">Content here</div></div>
<div id="divtwo"><div class="content">Content here</div></div>
<div id="divthree"><div class="content">Content here</div></div>
<div id="divfour"><div class="content">Content here</div></div>
<div id="divfive"><div class="content">Content here</div></div>
<div id="divsix"><div class="content">Content here</div></div>

css:

.content { width:960px; margin:auto;}
#divone { background-image: url(bg1.png); background-repeat: repeat;}
#divtwo { background-image: url(bg2.png); background-repeat: repeat;}
#divthree { background-image: url(bg1.png); background-repeat: repeat;}
#divfour { background-image: url(bg1.png); background-repeat: repeat;}
#divfive { background-image: url(bg1.png); background-repeat: repeat;}
#divsix { background-image: url(bg1.png); background-repeat: repeat;}

我做了一个小伙子,让你知道我在做什么http://jsfiddle.net/64H5p/

每次我想将div对齐到中心时,是否有更简单的方法而不添加.content?我正在处理的网站每页大约有100个。

5 个答案:

答案 0 :(得分:1)

你可以创建一个容器div,以margin为中心:0 auto然后把div放在里面,每个都有100%的宽度

答案 1 :(得分:1)

在你的css代码中试试这个

div[id^='div'] div { 
  width:120px;
  margin:auto;
}

DEMO

答案 2 :(得分:0)

为什么不在每个外包装div上使用text-align:center;? (divone,divtwo,......)

答案 3 :(得分:0)

 #divone, #divtwo, #divthree, #divfour, #divfive, #divsix {
     width:960px; 
     margin:0 auto;
 }

您可以组合选择器。

如果您仍想在div#divone中使用#divtwo,可以使用这样的选择器:#divone div, #divtwo div, #divthree div, ... {}

Demo

答案 4 :(得分:0)

我为你做了这个小问题:

http://jsfiddle.net/4V68d/

看看

或者看这里:

<div class="content">
<div id="divone">Content here</div>
<div id="divtwo">Content here</div>
<div id="divthree">Content here</div>
<div id="divfour">Content here</div>
<div id="divfive">Content here</div>
<div id="divsix">Content here</div>
</div>​

.content {margin:auto;}
.content div{text-align: center;}
#divone { background-image: url(bg1.png); background-repeat: repeat; background-color:red;}
#divtwo { background-image: url(bg2.png); background-repeat: repeat;background-color:blue;}
#divthree { background-image: url(bg1.png); background-repeat: repeat;background-color:yellow;}
#divfour { background-image: url(bg1.png); background-repeat: repeat;background-color:green;}
#divfive { background-image: url(bg1.png); background-repeat: repeat;background-color:pink;}
#divsix { background-image: url(bg1.png); background-repeat: repeat;background-color:grey;}​

如果您希望只有某些与中心对齐,请将类添加到要与中心对齐的div

像:

<div id="divone" class="centered">Content here</div>

.centered {margin: 0px auto;}