使用display:flex将div垂直居中于页面
时间: 2023-08-03 21:06:38 浏览: 58
使用 `display: flex` 属性也可以实现将 div 垂直居中于页面。您可以将 div 的父元素设置为 `display:flex` 并使用 `align-items` 属性将其垂直居中。如下所示:
```css
.parent {
display: flex;
align-items: center;
justify-content: center;
height: 100vh; /* 100% Viewport Height */
}
.child {
/* add your child element styles here */
}
```
在这个例子中,我们将 `.parent` 元素的高度设置为 `100vh`,这使得它占满整个视口高度。接下来,使用 `display: flex` 将其子元素水平和垂直居中。最后,您可以为 `.child` 元素添加任何其他样式,如背景颜色、边框等。
请注意,此方法需要设置父元素的高度,因此如果您的 div 高度是动态变化的,您可能需要使用 JavaScript 动态设置父元素的高度。
相关问题
div属性display: flex;设置垂直居中
使用display: flex;属性可以使元素成为一个弹性盒子,从而实现垂直居中。
具体实现方式如下:
1. 将父级元素设置为display: flex;属性。
2. 使用align-items: center;属性将子元素垂直居中。
示例代码如下:
```html
<style>
.container {
display: flex;
align-items: center;
height: 300px;
}
.box {
width: 100px;
height: 100px;
background-color: red;
}
</style>
<div class="container">
<div class="box"></div>
</div>
```
在上面的示例代码中,.container元素被设置为display: flex;属性,.box元素被垂直居中。同时,height属性也被设置为300px,以便更好地展示效果。
display: flex;下div居中
在使用display: flex属性进行div居中时,可以通过设置父容器的属性来实现。具体方法如下:
1. 使用justify-content属性实现水平居中[^1]:
```css
.container {
display: flex;
justify-content: center;
}
```
2. 使用align-items属性实现垂直居中[^2]:
```css
.container {
display: flex;
align-items: center;
}
```
3. 同时使用justify-content和align-items属性实现水平和垂直居中:
```css
.container {
display: flex;
justify-content: center;
align-items: center;
}
```
需要注意的是,以上方法都是基于父容器的高度已经设置好的情况下。如果父容器的高度是自适应的,上下居中效果可能不明显。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)