2014-01-28 137 views
0

我有一个div id,其中包含背景图片。图像的宽度是1020px,这正是我想要div box的大小。我想将它置于标题下的页面上,但我不希望表格或其中的任何文本居中。我认为我可以为div和其他元素创建div id/class来区别它们,但我仍然无法获得div id。我试过了text-align:center属性,但我没有任何运气。居中div id

这是我的CSS:

@charset "utf-8"; 
/* CSS Document */ 

body { 
    background:url(img/background_texture.jpg) no-repeat center center fixed; 
    background-size: cover; 
} 

#header { 
    text-align: center; 
    padding: 0px; 
    margin: 0px; 
} 

#header img { 
    vertical-align: bottom; 
} 

#content { 
    background-image:url(img/ContentBox.png); 
    background-repeat: no-repeat; 
    background-position:center; 
    padding: 0; 
    margin: 0; 
    width: 1020px; 
} 

这是基本的HTML结构

<!DOCTYPE html> 
<html> 
    <head> 
    <meta charset="utf-8"> 
    <title>Metra Train Schedule</title> 
    <link href="styles.css" rel="stylesheet" type="text/css" /> 
    </head> 

<body> 

<div id="header"><img src="img/Header.jpg" /></div> 

<div id="content"> 

    <table> 
    </table> 

    <table> 
    </table> 

</div> 

</body> 
</html> 

这是浏览器预览,你可以看到我在谈论更好地在这里。

enter image description here

回答

2

保证金汽车,结合的宽度是画面的小于100%时,将中心的元素。如果添加margin: 0 auto;到CSS的#内容,它应该做的伎俩:

#content { 
    ... 
    margin: 0 auto; 
} 

此处了解详情:http://learnlayout.com/margin-auto.html

+1

非常感谢。这就像一个魅力。 :) – DiscipleDavid

1

您可以使用margin-left: automargin-right: auto自动居中图像如果添加display: block它。

#header img { 
    display: block; 
    margin: 0 auto; /* shorthand for left, right auto and top,bottom 0 
} 

Live demo (click).

也许你想包装所有你的身体的HTML的一个容器中,风格这样说?

#container { 
    width: 1020px; 
    margin: 0 auto; 
} 

Live demo (click).

+0

这使得一切都变成了左对齐,包括头。 – DiscipleDavid

+0

这将使图像居中,他已经使用text-align:center创建了图像。但是,将头部CSS切换为#header {width:1020px;保证金:0汽车; },以便在对中策略中保持一致。 –

+0

@DiscipleDavid我不明白你的意思......你问它不会影响其他任何东西。 – m59

2

div {text-align:center;}不起作用FOR DIVS。常见的错误。

使用这个代替:

div {width:1020px;margin-left:auto;margin-right:auto} 

“自动”强制两边的保证金被默认的页面中的剩余空间的一半。这不会使div内的任何内容居中。它会为你完美工作。