实现任意元素居中

<style>
*{
padding: 0;
margin: 0;
}
.box{
width: 400px;
height: 400px;
border-radius: 200px;
background-color: #ccc;
margin:100px auto;
position: relative;
}
.rec{
width: 200px;
height: 200px;
background-color: red;
position: absolute;
/*定位的百分比是参照父容器的宽高*/
left: 50%;
top: 50%;
/*使用transform实现元素的居中 百分比是参照元素本身的宽高*/
transform: translate(-50%,-50%);
/*transform: translate(-50px,-50px);*/
}
</style>
</head>
<body>
<div class="box">
<div class="rec"></div>
</div>
posted @ 2018-12-26 23:38  lujieting0  阅读(208)  评论(0编辑  收藏  举报