您的位置:首页 > Web前端 > CSS

Css3元素浮动时居中

2016-07-22 20:46 423 查看


(1)使用margin:auto+position:absolute

Html:代码如下

<span style="font-family:KaiTi_GB2312;font-size:18px;">    <div class="container">
<div class="content">
使用margin:auto居中
</div>
</div></span>

Css:代码如下

<pre name="code" class="html"><span style="font-size:18px;">       <span style="font-family:KaiTi_GB2312;"> .container {
position: relative;
width: 400px;
height: 150px;
background: red;
}
.content{
width: 150px;
height: 50px;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
background: green;
}</span></span><span style="font-size: 18px;">
</span>



(2)使用 top与margin-top;left与margin-left相互矫正

<pre name="code" class="html"><span style="font-family:KaiTi_GB2312;font-size:18px;"></span><pre name="code" class="html"><pre name="code" class="html">.container {
position: relative;
width: 400px;
height: 150px;
background: red;
}
.content {
width: 150px;
height: 50px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -75px;
margin-top: -25px;
background: green;
}




(3)同上原理 使用 transform:translate(-50%,-50%)代替margin矫正
<span style="font-family:KaiTi_GB2312;font-size:18px;"></span><pre name="code" class="html">.container {
position: relative;
width: 400px;
height: 150px;
background: red;
}


.content {
width: 150px;
height: 50px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: green;
}


扩展:如果想实现拖出文档流居中,只需把父级变为position:reactive同理如果想实现永久居中则变为position:fixed

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: