您的位置:首页 > Web前端

[web前端学习笔记]定位的盒子居中显示

2017-08-16 11:09 1161 查看
哎,好久没接触前端,现在都要重新开始学习了,今天我们来讲如何对定位的盒子居中显示.

大家都知道对盒子居中显示有一个万金油的方法就是
margin: 0 auto;


但对于那只适用于没有脱离文档流的元素,用过定位的元素是不适用的

今天我就来讲一下对定位盒子也试用的方法

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>居中测试</title>
</head>
<style type="text/css">
.box{
width: 100%;
height: 500px;
position: relative;
background-color: aqua;
}
.test{
width: 400px;
height: 100px;
position: absolute;
background-color: black;
/*下面两句核心代码*/
left: 50%;
/*margin-left:只需要为该盒子的50%的宽度即可*/
margin-left: -200px;

}
</style>
<body>
<div class=" box">
<div class="test">

</div>
</div>
</body>
</html>


原理如下





现有一种用css3实现的方法

.test{
width: 400px;
height: 100px;
position: absolute;
background-color: black;
left: 50%;
/*把margin-left: -200px;改成这个效果一样*/
transform: translate(50%);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息