布局这么多页面,每次最麻烦的还是垂直居中的布局
今天遇到的是
|
1
2
3
4
5
6
7
|
<div class="con"> <img src=""> <div class="center">居中内容</div></div> |
父级被图片撑开,为了自适应不能设置高度。子级居中内容在图片上面,为了保证图片始终完全展示,不能作为背景图片,因此只有使用绝对定位使元素脱离文档。
因为子级没有高度和宽度所以:
.center{
position:absolute; top:50%; left:50%; margin-top:-50%; margin-left:-50%;
|
1
2
3
4
5
6
7
8
|
.center{ position: absolute; top:50%; left:50%; width:100%; transform:translate(-50%,-50%); text-align: center;} |
上面的方法不能使用
translate方法可以使用,但是会使子元素宽度缩小50%,影响里面的段落显示。
想到在center外再添加一个父级,center-con用来定位脱离文档流,再想办法使center居中
|
1
2
3
4
5
6
7
8
|
<div class="con"> <img src=""> <div class="center-con"> <div class="center">居中内容</div> </div> </div> |
网上百度了垂直居中的办法
方法1:table-cell
|
1
|
.center |
|
1
|
{ <br> display: table-cell;<br> vertical-align: middle; <br> text-align: center;<br> } |
这个方法使用最多,但center-con设置了display:table;后不管是height:100%;还是绝对定位,top:0;left:0;bottom:0;right:0;都不能使center-con的高度和父级con的高度一致,没办法实现垂直居中。
最后方法:
display:flex
|
1
2
3
4
5
|
.center-con{ display: flex; justify-content:center; align-items:Center;} |