- 普通行高居中,使用line-height, text-align
<div class="tx">text</div>
.tx { line-height: 40px; /* 文本垂直居中 */ text-align: center; /* 文本水平居中 */ }
- 块状元素水平居中,使用margin:0 auto;
<img class="img"/>
.img { display: block; width: 40px; height: 40px; margin-left: auto; margin-right: auto; }
- flex布局居中
<div class="flex-box"> <div class="flex-item"></div> <div class="flex-item"></div> </div>
.flex-box { display: flex; /* 水平方向,弹性布局 */ align-items: center; /* 垂直居中 */ justify-content: center; /* 水平居中 */ }
.flex-box { display: flex; flex-direction: column; /* 垂直方向,弹性布局 */ align-items: center; /* 水平居中 */ justify-content: center; /* 垂直居中 */ }
- 使用绝对定位居中
<div class="pos-r"> <div class="label"> </div> </div>
/* * 假设.pos-r 行高100px * .label 行高20px, 宽度20px * .label 作为一个标签需要显示在右边且垂直居中 */ .pos-r { position: relative; height: 100px; } .pos-r .label { width: 20px; height: 20px; margin-top: -10px; /* 自动减去.label高度的一半 */ position: absolute; right: 0; top: 50%; z-index: 100; }
如果高度不确定,则使用transform
/* * 假设.pos-r 行高100px * .label 行高20px, 宽度20px * .label 作为一个标签需要显示在右边且垂直居中 */ .pos-r { position: relative; height: 100px; } .pos-r .label { width: 20px; height: 20px; position: absolute; right: 0; top: 50%; z-index: 100; transform: translateY(-50%); /* 向上偏移自身50% */ }
-
图像内容显示的垂直水平居中
(1)使用img本身属性<img class="img" src="..."/>
.img { object-fit: contain; /* 如果图像比例与容器不符,则等比进行缩放 */ object-position: center; /* 图片内容居中 */ }
(2)使用背景图片的形式
<div class="img"></div>
.img { width: 40px; height: 40px; background-image: url("http://abc"); background-repeat:no-repeat; background-size: contain; background-position: center; }