我正在嘗試將DIV元素的內容居中,該元素的滾動條隱藏在父級後面。看起來是這樣的:如何居中DIV的同時隱藏它的滾動條?
HTML:
<div class="parent">
<div class="child">
<div class="content">
This should be centered! This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!
</div>
</div>
</div>
CSS:
.parent {
width: 300px; /* unknown width - 100%* - browser size */
height: 200px; /* unknown width - 100%* - broser size */
overflow: hidden;
background: #dedede;
}
.child {
width: 120%;
height: 100%;
overflow-y: scroll;
background: #000;
}
.content {
width: 150px;
margin: 0 auto;
background: #fff;
}
我已經嘗試了各種東西,但似乎沒有任何工作。
我想完成這個跨瀏覽器,如果用戶重新調整窗口大小仍然工作。我的問題是不同瀏覽器中的滾動條寬度變化爲,並且屏幕寬度也未知。
這是非常好的,但它仍然是2-3像素關閉。我有一個版本,我做了類似的工作,但仍然依賴於瀏覽器滾動條寬度。雖然謝謝! ;) – Teodors
我嘗試通過將.child寬度設置回100%並添加 - padding:0 17px; margin-left:-8px。 (這讓我相當接近中心,但它並不真正居中,瀏覽器仍然依賴) – Teodors
如果你願意使用JavaScript/jQuery,你可以獲得精確的居中。你需要做的是使用'.parent',然後將'.content'的'left'偏移量設置爲{.parent}的半寬減去.content的半寬然後,需要附加將JavaScript函數轉換爲onload/onresize事件。 –