2011-05-29 68 views
0

演示页:http://apps.pc-tips.in/play/DIV不居中,一个格是一个DIV不

在上面,含有“问任何问题&获得” DIV居中,但格方含行“的回答上“ 不是。为什么?两者的风格都相似。给定宽度,绝对位置,边距自动。

代码:

<!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> 

会有人想指出什么,我在这里失踪?

回答

1

正如kuroir的回答所说,如果你也使用绝对定位,则不能以这种方式居中元素。

你的“询问任何问题”div 不是居中,你已经给它与它的容器相同的宽度。

两者看起来不同的唯一原因是#topside容器上有text-align: center容器,而不是#bottomside容器上。

+0

谢谢所有,文本对齐中心做到了。现在看来很明显,margin:0 auto;不会以绝对中心为中心。 – 2011-05-29 21:36:31

+0

有趣的事实。我没有得到upvote :( – MarioRicalde 2011-05-30 20:02:49

1

当您添加position:absolute时,您无法通过margin:0 auto将元素居中。从.top删除position:absolute,它应该工作。

不知道你在努力达到什么目的,但是这几乎可以解决你的问题。请记住,您可以使用填充来“中心”内容。这将使您不必显式设置宽度。

1

你需要改变你的CSS,更新了“#bottomside”和“.TOP”风格像这样:

#bottomside { 
background-image: url(Untitled-4.jpg); 
height: 492px; 
position: relative; 
text-align: center; 
} 

.top { 
top: 3px; 
position: absolute; 
margin-left: auto; 
margin-right: auto; 
width: 100%; 
} 

的变化是自我解释,如果有一个困惑,让我知道。

+0

在旁注上,你可以优化你的CSS一个公平的位,删除不真正需要的项目/样式,但这是你可以看看以后!:) – thesocialgeek 2011-05-29 21:24:14