文章目录
图片水平垂直居中方法
1.方法一(position 元素宽高未知-transform: translate(-50%, -50%)):
图片宽高未知:
- 图片容器position属性不为static
- 图片:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
2.方法二(position 元素宽高未知-margin: auto)
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
3.方法三(flex):
移动端一般浏览器版本都比较高,所以可以大胆的使用flex布局
flex弹性布局:
- 容器
display: flex;
justify-content: center;
align-items: center;
4.方法四(position 宽高已知):
前提:图片宽高已知:
1.图片容器position属性不为static
2.图片:
position: absolute;
left: 50%;
top: 50%;
margin-left: -imgWidth/2;
margin-top: -imgHeight/2;
5.方法五(高度==line-height实现垂直居中):
利用高度==行高实现元素垂直居中
1.图片容器
text-align: center;
line-height: 容器height;
2.图片:(居中元素需要是行内块元素,或者是行内元素,
不能是块状元素)
vertical-align: middle;
6.方法六(display: table-cell):
缺点:
display: table的方法不支持ie6/ie7,
设置display: table之后可能会改变原有布局。
1.图片容器
display: table-cell;
text-align: center;
vertical-align: middle;
2.居中元素需要是行内块元素或者行内元素,不能是块状元素。
7.方法七(设置参照物):
1.容器水平对齐: text-align: center
2.垂直对齐
1》写参照物 span
2》参照物为行内块状元素,否则display: inline-block;
3》居中元素和参照物需要中线对齐, 都要加上vertical-align: middle;
4》参照物width: 0; height: 100%;