您的位置:首页 > 其它

如何居中一个浮动元素?

2016-03-15 19:40 871 查看
原文出处:http://blog.sina.com.cn/s/blog_8d322eff010192wx.html

回答:设置容器的浮动方式为相对定位
然后确定容器的宽高 比如宽500 高 300 的层

然后设置层的外边距

[html] view
plain copy







<!DOCTYPE HTML>

<html>

<head>

<style type="text/css">

div{

width: 500px;

height: 300px;

margin: -150px 0 0 -250px;

position: absolute;

left: 50%;

top: 50%;

background-color: yellow;

}

</style>

</head>

<body>

<div>

元素居中

</div>

</body>

</html>

另一例:

转自:http://zhidao.baidu.com/link?url=odE_aNuRcMMFNPoCecdRihon-WKS7gg2gsj5HnyB3ekvV9o5n4MzObKEFTzPRA_3UOkl0dqhWCcxmXDgz9kGqa


<style type="text/css">

<!--
div {
position:absolute;
top:50%;
left:50%;
margin:-150px 0 0 -200px;
width:400px;
height:300px;
border:1px solid #008800;
}
-->
</style>
<div>让层垂直居中于浏览器窗口</div>
其实解决的思路是这样的:首们需要position:absolute;绝对定位。而层的定位点,使用外补丁margin负值的方法。负值的大小为层自身宽度高度除以二。
如:一个层宽度是400,高度是300。使用绝对定位距离上部与左部都设置成50%。而margin-top的值为-150。<a target=_blank target="_blank" class="inner-link decor-none" href="http://zhidao.baidu.com/search?word=margin-left&fr=qb_search_exp&ie=utf8" rel="nofollow" style="color: rgb(45, 100, 179); text-decoration: none;">margin-left</a>的值为-200。这样我们就实现了层垂直居中于浏览器的样式编写

如果你是想让div垂直居中与div,那么你可以在父级div上加一个position:relative即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: