[英]center floating div horizontally
我想要一個水平居中的“浮動”div,即即使用戶滾動也始終位於屏幕頂部的div。
使用以下CSS,我將div完全放在左側:
#guiBar {
margin-left: auto;
margin-right: auto;
position: fixed;
}
margin: 0 auto
也沒有幫助(大概是因為這不能與position: fixed
一起工作position: fixed
?
我真的不在乎解決方案如何工作,所以javascript或一些html5技巧將與純css一樣好。 我已經嘗試過從starx找到的解決方案,但這似乎也不適用於position:fixed。 還有這個也不起作用(即它是左中心的 - 不確定是否有一些<input class="guiButton" type="image" src="/icons/some.png" />
有一個固定的大小他的定義。)
如果元素是固定寬度(例如寬度:400px),則可以使用left和top屬性以及margin屬性:
#guiBar
{
position:fixed;
left:50%;
margin-left:-200px; /*half the width*/
}
演示: http : //jsfiddle.net/VtqQD/1/show
資料來源: http : //jsfiddle.net/VtqQD/1
編輯:感謝Xander指出問題只是關於水平定位。
HTML
<div id="subject">
<div id="predicate">
Read Me!
</div>
</div>
CSS
#subject {
position:fixed;
top:0px;
left:0px;
width:100%;
height:100%;
}
#predicate {
position:relative;
top:50%;
margin:-20px auto auto auto; /*half of height*/
width:140px;
height:40px;
background:#b4da55;
}
您可以使用javascript使用scrollHieght和scrollWidth來查找父div的高度和寬度。 然后使用這些值除以2得到div中心的值。 然后通過想要放在頂部的div的尺寸來抵消它。
如果你想要整個屏幕/窗口的中心使用window.innerHeight和window.innerWidth然后除以2並用你的div偏移。
我做了一個小例子:
<html>
<head>
<style type="text/css">
body { margin: 0; }
#wrapper { width: 500px; margin: 0 auto; }
#top { margin: 0 auto; width: inherit; background: red; position: fixed; }
</style>
</head>
<body>
<div id="wrapper">
<div id="top">
foo
</div>
</div>
</body>
</html>
我希望它會對你有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.