<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>水平垂直居中与body</title>
<link rel="stylesheet" type="text/css" href="./css/index2.css" >
</head>
<body>
<div class="absolute0marginauto">
绝对定位 上下左右都是0px,margin使用auto
</div>
<div class="flexcenterparent">
<div class="flexcentersub">
使用css3的 flex模式 justify-content:center aligin-items:center模式居中,但这个有点不适合在body中垂直水平居中,因为如果body都设置这种模式,那它里面的元素都水平垂直剧终了
</div>
</div>
<div class="marginwidhthalf">
使用绝对定位 left50% top50% 然后 margin-left:div宽度高度一半 margin-top:div高度一半,
这种需要知道本身的width height
</div>
<div class="absolutetransform">
使用绝对定位 然后使用transform(-50%,-50%),进行移动,这种方法,不需要知道宽高,
我不需要知道宽高
</div>
</body>
</html>
--css
*{
margin: 0px;
padding: 0px;
}
html,body{
width: 100%;
height: 100%;
}
.absolute0marginauto{
width: 100px;
height: 100px;
position: absolute;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
margin: auto;
background: brown;
}
.flexcenterparent{
width: 300px;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
border: 2px solid red;
}
.flexcentersub{
width: 200px;
height: 200px;
border: 2px solid blue;
}
.marginwidhthalf{
width: 200px;
height: 200px;
border: 2px solid violet;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
.absolutetransform{
border: 4px solid darkmagenta;
color: darkorange;
position: absolute;
top: 50%;/*这个的50%是父元素的50%,二translate 50%是div本身的50%*/
left: 50%;
transform: translate(-50%,-50%);
}
顺便说下 文在在div中水平居中,使用 text-algin:center 垂直居中line-height:divheight