css定位水平垂直居中
时间: 2023-11-20 14:57:48 浏览: 94
以下是五种CSS定位水平垂直居中的方法:
1.利用margin:auto
```css
.container {
position: relative;}
.center {
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
margin: auto;
}
```
2.利用position: absolute
```css
.container {
position: relative;
}
.center {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
}
```
3.弹性盒子
```css
.container {
display: flex;
justify-content: center;
align-items: center;
}
```
4.利用水平对齐和行高
```css
.container {
height: 200px;
line-height: 200px;
text-align: center;
}
.center {
display: inline-block;
vertical-align: middle;
line-height: normal;
}
```
5.grid
```css
.container {
display: grid;
}
.center {
justify-self: center;
align-self: center;
}
```
阅读全文