Demo Page: http://apps.pc-tips.in/play/
In the above, the div containing “Ask any question & get” is centered, but the div containg the line “answers on” is not. why? Both have been styled similarly. given width, absolute position, margin auto.
The code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
div {
margin:0 ;
padding:0 ;
}
#sidebar {
height: 600px;
width: 200px;
}
#topside {
height: 108px;
background-image: url(Untitled-3.jpg);
background-repeat: repeat-x;
text-align: center;
position: relative;
}
.down {
bottom: 3px;
position: absolute;
margin: auto;
width: 200px;
}
#bottomside {
background-image: url(Untitled-4.jpg);
height: 492px;
position: relative;
}
#wrapper #sidebar #topside {
color: #FFF;
font-size: 0.9em;
font-weight: bold;
}
.delhi {
font-size: 1.8em;
}
.top {
top: 3px;
position: absolute;
margin-left: auto;
margin-right: auto;
width: 100px;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="sidebar">
<div id="topside"><br /> <span class="delhi">Delhi </span> Questions and answers.
<div class="down">
Ask any question & get
</div>
</div>
<div id="bottomside">
<div class="top"> answers on </div>
</div>
</div>
</div>
</body>
</html>
would anyone like to point out what I am missing here?
As kuroir’s answer says, you can’t center elements this way if you’re also using absolute positioning.
Your “ask any question” div isn’t being centered, you’ve given it the same width as its container.
The only reason the two look different is that there’s a
text-align: centeron the#topsidecontainer, and not on the#bottomsidecontainer.