再会。
我知道如果你想将 div 绝对居中,你可以这样做:
<div id="parent">
<div id="child">blahblah</div>
</div>
CSS:
#parent{
width: 500px;
height: 500px;
position: absolute; /*(or relative)*/
top: 50%;
left: 50%;
margin-top: -250px;
margin-left: -250px;
text-align: center;
}
如果父div是流体div怎么办?你如何绝对居中它的意思:
#parent{
max-width: 500px;
max-height: 500px;
top: 50%; ->is this right?
left: 50%; -> is this right?
margin-top: ???;
margin-left: ???;
text-align: center;
}
As the width
and height
是流畅的,你需要使用 javascript 或 jQuery。只需添加以下代码即可head
tag. (下面的例子是在javascript中)
<script>
window.onresize = function(){
//To work even on resize
getToMiddle();
}
window.onload = function(){
getToMiddle();
}
function getToMiddle(){
var box = document.getElementById('parent');
var height = box.offsetHeight;
var width = box.offsetWidth;
box.style.top = -(height/2);
box.style.left = -(width/2);
}
</script>
你的CSS将是这样的:
#parent{
max-width: 500px;
max-height: 500px;
background-color:green;
position:absolute;
top: 50%;
left: 50%;
/* width: 10%;
height: 10%; */
}
为了测试,给width: 10%; and height: 10%
工作小提琴 http://jsbin.com/ewizad/7/edit
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)