html让元素水平垂直居中的方法
时间: 2023-12-20 10:06:05 浏览: 73
1. 使用Flexbox布局
在父元素上使用display: flex;和align-items: center;和justify-content: center;属性可以让子元素垂直和水平居中。
```html
<div class="parent">
<div class="child">Hello World</div>
</div>
<style>
.parent {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
.child {
width: 200px;
height: 200px;
background-color: #ccc;
}
</style>
```
2. 使用position和transform属性
可以使用position: absolute;、top: 50%;和left: 50%;属性将元素定位到父元素的中心,然后使用transform属性将元素向上移动一半高度和向左移动一半宽度的值。
```html
<div class="parent">
<div class="child">Hello World</div>
</div>
<style>
.parent {
position: relative;
height: 100vh;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background-color: #ccc;
}
</style>
```
3. 使用table和table-cell属性
可以将父元素的display属性设置为table,子元素的display属性设置为table-cell,并将vertical-align和text-align属性设置为middle和center。
```html
<div class="parent">
<div class="child">Hello World</div>
</div>
<style>
.parent {
display: table;
height: 100vh;
width: 100%;
text-align: center;
}
.child {
display: table-cell;
vertical-align: middle;
width: 200px;
height: 200px;
background-color: #ccc;
}
</style>
```
阅读全文
相关推荐
















