我會讓你第一眼看到的代碼,然後告訴你,我的問題是什麼:不應該「text-align:center;」應用於絕對定位的元素,對其子元素不做任何事情?
Tinkerbin:http://tinkerbin.com/x8iGCFsZ
<style>
div.container{
height: 200px;
width: 200px;
background-color:red;
margin-top: 10px;
}
div.subContainer{
position: relative;
text-align: center;
}
div.inner{
position: absolute;
background-color:yellow;
width: 150px;
}
</style>
<div class="container">
<div class="subContainer">
<div class="inner">bananas for breakfast</div>
</div>
</div>
那麼,根據教科書,text-align: center;
,當應用於父元素,如果他們的子元素只有display: inline;
,那麼它只會集中它。
因此,正如你所期待,因爲<div>
具有默認的顯示設置爲阻止(display:block;
)應用於父div.subContainer
的text-align: center;
沒有做任何事情到其子div.inner
。
一切都很好。沒有什麼奇怪的。當我嘗試.inner
元素上使用<span>
,而不是<div>
我的問題引起的,我定位它絕對(position: absolute;
)—其中,因爲你知道力的變化顯示,從默認的內聯,以阻止。
請看:
<style>
div.container{
height: 200px;
width: 200px;
background-color:red;
margin-top: 10px;
}
div.subContainer{
position: relative;
text-align: center;
}
span.inner{
position: absolute;
background-color:yellow;
width: 150px;
}
</style>
<div class="container">
<div class="subContainer">
<span class="inner">bananas for breakfast</span>
</div>
</div>
會發生什麼情況是怪異。儘管有塊的強制顯示值(感謝position: absolute;
),跨度仍然居中。而且更重要的是,居中實際上很奇怪。它將塊的左側並與包含元素的中心對齊,而不是像往常一樣將兩個中心對齊。
行爲是固定的—開始時像一個塊—,當我手動設置span.inner
阻止顯示。
span.inner{
position: absolute;
display: block;
background-color:yellow;
width: 150px;
}
那麼,這裏發生了什麼?絕對定位不是強制改變顯示器以阻止?爲什麼中心奇怪?
說真的,這是一個很棒的答案:** + 1 ** – 2012-02-09 23:10:04
是的,很好的回答。 – ScottS 2012-02-09 23:23:51
嗨。感謝你的回答。我想我明白了。我在哪裏可以閱讀更多關於這個東西?我還沒有閱讀Eric Meyer的權威CSS指南。它是否涵蓋這些細節? – banzomaikaka 2012-02-09 23:29:42