2013-01-08 39 views
0

不知道什麼,我越來越錯在這裏,但讓我們說我有兩個div和h1元素(或P1)爲此事看起來像這樣:定位嵌套元素WRT到它的直接父

<div class="wrapper"> 
<div class="top"> 
    <h1>Content header</h1> 
</div> 
</div> 

我希望我的元素出現在內部div的「中間位置」,也就是它的直接父對象。爲了達到這個目的,我給它一個保證金頂部:50%的利潤率:50%,理解這將使其正好朝向div的中間中間位置。但是它確實把它放在中間,但它並沒有把它帶到中心。事實上,它似乎將自己定位於外層div,即帶有類封裝的外層div。

我已經重新使用這個這裏的jsfiddle:

http://jsfiddle.net/KLRsN/

我是否指定選擇錯誤的或者是我的定位本身就是不正確的?

+0

你需要H1是「中央中」到.TOP DIV?或.top div到'center middle'到.wrapper div? – Sowmya

回答

1

-the ANS心不是完全正確的文本將仍然不能完全垂直居中的上方。

.wrapper{ 
    margin:5px; 
    max-height:250px; 
    min-height:250px;/*not required only height:250px will do*/ 
    border:1px solid green; 
} 

.content 
{ 
    margin:5px; 
    border:1px solid black; 
    height:100px;/*you have to give the parent element a height and a width within which you wish to center*/ 
    width:100px; 
    position:relative;/*giving it a position relative so that anything inside it will be positioned absolutely relative to this container*/ 
    text-align:center;/*aligning the h1 to the center*/ 
} 
.content h1{ 
border:1px solid black; 
position:absolute; 
top:50%; 
    left:50%; 
    line-height:50px; 
    width:50px; 
    margin-left:-25px;/*half the width of the h1 so that it exactly centers*/ 
    margin-top:-25px;/*half the height of the h1 so that it exactly centers*/ 
} 

解釋:

html

-ever元件是矩形框,以便施加margin-top:50%的是,框的頂部對準的父元素的50%並且不箱內文本的形式。 - 這就是文本與中心不完全一致的原因。

- 同樣重要的是提供父元素(其中你希望居中h1)的寬度和高度。

正確的做你正在尋找的方法是通過使用絕對和相對定位。

-give的.container的相對位置值和h1的絕對

-by給H1的寬度和高度的值,我們然後施加負左邊距等於寬度和負上邊距半等於高度的一半,以便文本完全居中。

  • 也爲更多的定位 - 請查看以下link
+0

謝謝,因爲按照我在js提琴中指定的CSS工作,所以我投票/向你提出正確的答案。雖然有一個小問題,但內部div(.content)必須是position:絕對的,因爲對於特定的動畫它是如此。我們在這種情況下做什麼? –

+0

如果一個元素(在本例中爲.h1)具有'position:absolute',則包含區塊由最近的祖先(本例中爲.content)與'絕對','相對'或'固定'。 所以你可以給.content div一個絕對的位置。 http://www.w3.org/TR/CSS2/visudet.html#containing-block-details –

0

如果要在中間顯示文本內容,可以使用text-align:center,或者可以將寬度應用於h1標記並使用margin:auto。垂直居中使用相對位置和頂部:50%。試試這個CSS

.wrapper{ 
    height:250px; 
    min-height:250px; 
    border:1px solid green; 
    } 

.content{ 
    position:relative; 
    top:50%; 
    border:1px solid black; 
} 
.content h1{ 
    border:1px solid blue; 
    margin:auto; 
    width:100px; 
    background:red 
} 

希望它可以幫助