写博客主要是用来总结、巩固知识点,加深本身对这个知识点的理解。同时但愿能帮助到有须要的人。若有不正确的地方。能够在评论区指出。大家的支持。是我不断进步的源泉。css
原本想把这个知识点放在这篇博客中讲的,可是这里涉及的内容还挺多的。因而就把它单独拉出来写了。html
下面的内容使用到了flex的布局方式。有关flex的详细使用方法和兼容性。这里就不详细讲述了,能够看这篇文章前端
这里讨论的是子元素为块级元素的水平垂直居中方案。其余行内元素的的方案能够看这大佬的文章16种方法实现水平居中垂直居中html5
html:css3
<div class="parent">
<div class="child"></div>
</div>
复制代码
css:git
.parent {
position: relative;
width: 600px;
height: 600px;
margin: auto;
border: 1px solid red;
}
.child {
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
width: 100px;
height: 100px;
border: 1px solid blue;
}
复制代码
原理:这个的实现方法原理仍是很好理解的。相对父元素定位,距上边和左边个一半,而后在减去子元素的一半。github
css:bash
.parent {
position: relative;
width: 600px;
height: 600px;
margin: auto;
border: 1px solid red;
}
.child {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100px;
height: 100px;
border: 1px solid blue;
}
复制代码
原理:这个方法的实现原理看了张鑫旭大神的博客本身仍是一直半解的。若是有同窗知道能够在评论区探讨下。 实现原理看这里wordpress
css:布局
.parent {
position: relative;
width: 600px;
height: 600px;
margin: auto;
border: 1px solid red;
}
.child {
position: absolute;
width: 100px;
height: 100px;
border: 1px solid blue;
}
.method3 {
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
复制代码
原理:这种方法的实现原理其实跟固定宽高的方法一是同样的。可是他有一个有点就是不须要知道元素的宽高。主要是经过transform中translate偏移的百分比值是相对于自身大小的。因此就能够实现不知道宽高仍是能够实现垂直水平居中。
css:
.parent {
display: flex;
justify-content: center;
align-items: center;
width: 600px;
height: 600px;
margin: auto;
border: 1px solid red;
}
.child {
width: 100px;
height: 100px;
border: 1px solid blue;
}
复制代码
原理:经过justify-content和align-items两个属性来实现水平垂直居中,一个定义的是水平轴山上的对齐方式,另外一个则定义的是垂直轴上的对齐方式。
详细代码在这里:github.com/Leo928/html…
以上部份内容参考自其它文章。能够点击连接查看原文。
最后:若是讲诉不当的地方。请在评论区指出。大家的支持,是我不断进步的源泉。
参考资料