css居中代码怎么写
一、水平居中
1. 对于行内元素或行内块元素,只需将父容器的文本对齐方式设置为居中即可。
```css
.parent {
text-align: center; / 父容器内的文字水平居中 /
}
```
2. 对于已知宽度的块级元素,可以设置左右外边距自动,使元素在父容器中水平居中。
```css
.child {
width: 200px; / 设置子元素宽度 /
margin: 0 auto; / 左右外边距自动,实现水平居中 /
}
```
3. 使用Flexbox布局,通过justify-content属性轻松实现水平居中。
```css
.parent {
display: flex; / 采用Flexbox布局 /
justify-content: center; / 子元素在父容器中水平居中 /
}
```
二、垂直居中
1. 对于单行文本,可以通过设置父容器的高度与行高相等来实现垂直居中。
```css
.parent {
height: 100px; / 设置父容器高度 /
line-height: 100px; / 行高等于容器高度,文本垂直居中 /
}
```
2. 利用Flexbox布局,通过align-items属性实现垂直居中。
```css
.parent {
display: flex; / 采用Flexbox布局 /
align-items: center; / 子元素在父容器中垂直居中 /
}
```
3. 对于需要绝对定位的元素,通过设置top为50%和transform属性实现垂直居中。
```css
.child {
position: absolute; / 绝对定位 /
top: 50%; / 距离容器顶部50% /
transform: translateY(-50%); / 向上移动自身高度的50%,实现垂直居中 /
}
```