水平居中和水平垂直居中demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
body,html{
position: relative;
width: 100%;
min-height: 100%;
height: 100%;
}
body{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background-color: rgba(175, 80, 177, 0.56);
}
/*1:方式一:给div设置一个宽度;然后添加margin:0 auto属性*/
.div1{
margin: 0 auto;
background-color: #0D3349;
height: 60px;
width: 30%;
}
/*2:让绝对定位的div居中*/
.div2{
position:absolute;
margin: auto;
/*水平居中*/
right: 0;
left:0;
/*垂直居中*/
/*bottom:0;*/
/*top:0;*/
top:60px;
width: 30%;
height: 60px;
background-color: #494737;
}
.div3{
position:absolute;
margin: auto;
/*水平居中*/
left:0;
right: 0;
top:125px;
/*垂直居中*/
/*top:0;*/
/*bottom:0;*/
width: 30%;
height: 360px;
background-color: #494737;
}
/*水平,垂直居中*/
.one {
position: relative; /* 相对定位或绝对定位均可 */
width:300px;
height:200px;
top: 50%;
left: 50%;
margin: -100px 0 0 -150px; /* 外边距为自身宽高的一半 */
background-color: rgba(13, 13, 17, 0.78); /* 方便看效果 */
}
.two{
position: absolute; /* 相对定位或绝对定位均可 */
width:250px;
height:160px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: pink; /* 方便看效果 */
}
.div4 {
display: flex;
align-items: center; /* 垂直居中 */
justify-content: center; /* 水平居中 */
}
.three{
width: 100px;
height: 100px;
background-color: pink; /* 方便看效果 */
}
</style>
<body>
<div class="div1" style=""></div>
<div class="div2"></div>
<div class="div3">
<div class="one">方式一</div>
<div class="two">方式二</div>
</div>
<div class="div4" style="position:absolute;margin: auto;top:490px;left:0;right: 0;width: 30%;height: 360px;background-color: #494737">
<div class="three">方式三</div>
</div>
</body>
</html>