transform: translate(50%, 50%)
为什么能够使一个元素水平垂直居中?
怪我咯2017-04-17 11:40:22
Writing like this does not center an element horizontally and vertically. It can only make the element translate half of its own width in the positive direction of the x-axis and y-axis at the current position.
I answered a question before. You can take a look at it. It may be of some help.
translate
ringa_lee2017-04-17 11:40:22
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<!--author:Vace_Vlm(ocdo@qq.com),create:2016年5月21日 下午10:45-->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>title</title>
<style>
*{
padding: 0;margin: 0;
}
html,body{
width:100%;
height:100%;
}
.box{
position:relative;
top:50%;
left:50%;
width:200px;
height:200px;
background:red;
transform:translate(-50%,-50%);
transform-origin:50% 50%;
}
</style>
</head>
<body>
<p class="box"></p>
</body>
</html>
巴扎黑2017-04-17 11:40:22
Writing like this cannot be directly centered, but can be positioned, and then left:50%; At this time, the positioning origin is the positioning element of the parent layer, and then use translateX(-50%); at this time, it is moved to the left relative to the element itself. Half, the final effect is exactly centered.