2016-10-22 60 views
2

我見過的模式在別人的代碼在網站上爲中心元素:CSS:位置:絕對值與邊距:自動居中 - 這是如何工作的?

img { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    margin: auto; 
 
}
<img src="https://placebear.com/200/300" alt="picture-one" />

它工作正常。毫無疑問 !

但我無法想象CSS代碼實際上做了什麼。

我見過類似的代碼,其中使用了定位來將子元素擴展爲其父元素的大小。

#child { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    background-color: lime; 
 
} 
 

 
#wrap { 
 
    width: 100%; 
 
    height: 800px; 
 
}
<div id="wrap"> 
 
    <div id="child"></div> 
 
</div>

但這裏是沒有意義的我。

有人能解釋我這些第一次顯示的技術是如何工作的嗎?

單個屬性做了什麼以及它如何最終實現它的結果?

我將不勝感激。

回答

2

#child { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    height: 100px; 
 
    width: 250px; 
 
    margin: auto; 
 
    background-color: lime; 
 
} 
 

 
#wrap { 
 
    width: 100%; 
 
    height: 800px; 
 
}
<div id="wrap"> 
 
    <div id="child"></div> 
 
</div>

這是因爲圖像有其默認寬度和高度。

當您使用

position: absolute; 
top: 0; 
left: 0; 
right: 0; 
bottom: 0; 

元素將得到窗口的大小和元素位置的這裏面。

#child { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    height: 100px; 
 
    width: 250px; 
 
    margin: auto; 
 
    background-color: lime; 
 
} 
 

 
#wrap { 
 
    width: 100%; 
 
    height: 800px; 
 
    position: relative; 
 
}
<div id="wrap"> 
 
    <div id="child"></div> 
 
</div>

所以,如果你把相對位置#wrap,位置絕對#child將調整到父。

希望它有幫助!乾杯!

1

position: absolute允許您設置元素距離整個頁面邊緣的頂部,底部,右側和左側的距離。

在第二個示例中,您甚至認爲#wrap設置爲800px的高度,因此頁面各邊的#child距離設置爲0.因此它覆蓋了整個頁面!

希望這有助於!

0

#inner { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    height: 100px; 
 
    width: 250px; 
 
    margin: auto; 
 
    background-color: #000; border:1px solid #fff; 
 
} 
 

 
#container { 
 
    width: 100%; 
 
    height: 800px; 
 
}
<div id="container"> 
 
    <div id="inner"></div> 
 
</div>

相關問題