Center a div inside another div
I'm trying to set a div centered inside another div.
This is the html page:
<body>
<div id="divParent">
<div id="divHeader" >
<div id="divHeaderText">
</div>
</div>
<div id="divBody">
</div>
</div>
</body>
And this the style:
#divHeader {
background-color: #C7C7C7;
font-family: 开发者_运维知识库Verdana, Geneva, Tahoma, sans-serif;
height: 80px;
margin-bottom: 2px;
}
#divBody {
background-image: url('images/GradientBackground.png');
background-repeat: repeat-x;
height: 300px;
}
#divHeaderText {
margin: auto;
width: 90%;
height: 80%;
background-color: #00FF00;
}
Why the smallest div doesn't left a space on its top?
Your question is unclear.
If you're trying to vertically center the #divHeaderText
within #divHeader
, try adding margin-top: 13px;
.
margin:auto does not work for vertical alignment. You must give an exact number in px, em, etc. In your example, this shouldn't be an issue, since you know the height of the parent container.
For centering horizontally, you can use text-align:center on inline elements or margin:0 auto with a set width on containers and block level elements.
For vertical centering of text, you can set the line-height property equal to the height of the containing div.
To center a div horizontally, you can apply a margin-top property to space it away into the center.
Please note that design questions are more appropriate for http://www.doctype.com/ as SO is largely geared towards server-side languages and application programming.
#divHeaderText {
margin: auto;
width: 90%;
height: 64px; /* 80% of 80px */
margin-top: 8px; /* (80 - 64) / 2 = 8 */
background-color: #00FF00;
}
精彩评论