代码复制马上可以看到效果,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
div {
height: 200px;
120px;
border: 1px solid red;
}
p {
height: 100px;
60px;
margin: 0;
padding: 0;
border: 1px solid blue;
}
h6 {
height: 30px;
border: 1px solid green;
line-height: 30px;
}
.parent1 {
display: flex;
justify-content: center;
align-items: center;
}
.parent2 {
position: relative;
display: inline-block;
}
.son2 {
position: absolute;
left: 50%;
transform: translate(-50%,0);
}
.rela {
position: relative;
}
.son3 {
position: absolute;
left: 50%;
margin-left: -30px;
}
.son4 {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
.h {
height: 100px;
200px;
}
.h:after {
content: '';
display: inline-block;
vertical-align: middle;
height: 100%
}
.hson {
height: 40px;
display: inline;
}
.h1 {
display: table;
}
.hson1 {
display: table-cell;
vertical-align: middle;
}
.hson2 {
position: absolute;
top: 50%;
transform: translate(0,-50%);
}
</style>
</head>
<body>
<!-- 水平居中 -->
1、行内元素
<div style="text-align: center;">
<a href="">asdf</a>
</div>
2、块级元素
<div >
<p style="margin: 0 auto"></p>
</div>
3、flex布局
<div class="parent1">
<p class="son"></p>
</div>
4、绝对定位和transform属性
<div class="parent2">
<p class="son2"></p>
</div>
5、绝对定位以及负值margin-left
</div><div class="rela">
<p class="son3"></p>
</div>
6、绝对定位以及left:0;right: 0;margin: 0 auto
</div><div class="rela">
<p class="son4"></p>
</div>
<!-- 垂直居中 -->
1、是单行文本
<h6>可以垂直居中没有骗人哦</h6>
2、行内块级元素
<div class="h">
<div class="hson">asdas</div>
</div>
3、高度不定
<div class="h1">
<div class="hson1">3adfg14sag</div>
</div>
4、flex布局 水平居中样式中写了
5、transform
<div class='rela'>
<p class="hson2"></p>
</div>
6、元素高度固定
<div class='rela'>
<div style="position:absolute;top:50%;height:40px;margin-top:-20px;"></div>
</div>
7、父元素相对定位,子元素如下样式
<div class='rela'>
<p style="position:absolute;top:0; bottom: 0;margin: auto 0"></p>
</div>
</body>
</html>