2011-08-27 51 views
4

如何将页面内容居中放置,使其以每种屏幕大小为中心?例如,如果我调整了我的浏览器的Allegorithmic,则中心内容将向左移动,直到它到达浏览器窗口。有某些背景元素无限地水平延伸(顶部为深灰色,中间为浅灰色等)。我可以在我的笔记本电脑和iMac上打开此网站,并将其集中。我认为我可能会使用绝对定位来将内容从左侧移动x像素,但这不起作用,因为以小屏幕为中心的300像素不会将其集中在大屏幕上。HTML/CSS内容始终居中

因此,本质上我想重复Allegorithmic网站的功能,具有横向无限的背景,但有某些内容始终保持“居中”。

回答

5

如果你想要元素总是居中使用margin: 0 auto;在它的样式。

#yourElement{ 
    margin: 0 auto; 
} 

W3.org reference for centering things using CSS

要获得背景元素,以延长整个页面长度只给他们100%的宽度,然后进行内部的子容器,并给他们相同的样式以上。我敢打赌,你给出的例子只是用一个高度为1px的线条在背景上看起来。

Example

Example with image bg

标记

<div id="background"> 
    <div id="content"> 
    </div> 
</div> 

CSS

#background{ 
    width: 100%; 
} 
#content{ 
    width: 960px; 
    margin: 0 auto; 
} 
0

试试这个 -

.center{ 
    margin: 0 auto; 
    position: relative; 
} 

auto应该对齐页面内容根据浏览器的尺寸调整到中心留下的空间(左,右)。

0

您可以为每个“级别”定义内部div的容器。

<div id="first" class="container"><div class="inner"> 
    first content goes there 
</div></div> 
<div id="second" class="container"><div class="inner"> 
    another content goes there 
</div></div> 
... 
... 
... 

,并与CSS样式它,使用ID为每个容器自定义样式(这些都是100%的宽度,使他们有充分的BG)

.container { 
    background: red; 
    text-align: center; 
} 
.container > .inner { 
    margin: 0 auto; 
    width: 960px; 
    text-align: left; 
} 
0

HTML

<div id="wrapper"> 
    <header> 
     <nav> 
     .... 
     </nav> 
    </header> 

    <div id="main"> 
     ..... 
    </div> 
</div> 

CSS

#wrapper { 
    width: 960px /* whatever you wanted but there has to be a width*/ 
    margin: 0 auto; 
} 

这会包裹一个以你的页面的全部内容为中心。

希望这会有所帮助。