盒子水平垂直居中的详细代码
时间: 2024-02-20 10:01:49 浏览: 71
好的,以下是几种方法的详细代码:
1. 使用 margin 属性:
```html
<div class="container">
<div class="box"></div>
</div>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.box {
width: 200px;
height: 200px;
background-color: #ccc;
}
</style>
```
2. 使用绝对定位和 transform 属性:
```html
<div class="container">
<div class="box"></div>
</div>
<style>
.container {
position: relative;
height: 100vh;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background-color: #ccc;
}
</style>
```
3. 使用 flex 布局:
```html
<div class="container">
<div class="box"></div>
</div>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.box {
width: 200px;
height: 200px;
background-color: #ccc;
}
</style>
```
4. 使用 table 和 table-cell 属性:
```html
<div class="container">
<div class="box"></div>
</div>
<style>
.container {
display: table;
height: 100vh;
width: 100%;
text-align: center;
}
.box {
display: table-cell;
vertical-align: middle;
width: 200px;
height: 200px;
background-color: #ccc;
}
</style>
```
5. 使用 grid 布局:
```html
<div class="container">
<div class="box"></div>
</div>
<style>
.container {
display: grid;
justify-content: center;
align-items: center;
height: 100vh;
}
.box {
width: 200px;
height: 200px;
background-color: #ccc;
}
</style>
```
阅读全文