文字垂直居中
div {height: 40;line-height: 40px;}
原理
让元素的高度等于文本行高
文字水平居中
div {width: 100px;margin: 0 auto;text-align: center;}
块元素水平居中
div {width: 100px;height: 100px;margin: 0 auto;}
图片与文字垂直居中
img {vertical-align: middle;}
| 属性值 | 描述 |
|---|---|
| baseline | 与父元素基线对齐 (默认值) |
| top | 顶部对齐 |
| middle | 中间对齐 |
| bottom | 底部对齐 |

- 只针对行内元素或者行内块元素有效
块元素水平垂直居中
* {margin: 0;padding: 0;}div {position: relative;width: 300px;height: 300px;background-color: skyblue;}div p{position: absolute;width: 100px;height: 100px;background-color: slateblue;top: 50%;left: 50%;transform: translate(-50%, -50%);}
flex居中
div {
display: flex;
justify-content: center;
align-conetnt: center;
align-items: center;
}
