如何使用 CSS 的 Flexbox 属性使 <div> 居中?
我们可以使用 Flexbox 的 justify-content 属性和 align-item 属性在 CSS 中使 <div> 居中。这两个属性响应迅速且易于使用,因此很受欢迎。在本文中,我们将学习如何使 <div> 居中。使用 Flexbox 属性。
使用 align-items 和 justify-content 属性
使用 Flexbox 使 div 居中最常见的方法是结合使用 Flexbox 的 justify-content 和 align-items 属性。
justify-content 属性会使 div 水平居中。
align-items 属性会使 div 垂直居中。
如果您只想在一个方向上居中,即垂直或水平居中,我们应该只使用我们提到的属性中的一个。
使用 align-items 和 justify-contents 使子元素水平和垂直居中。
示例
<!DOCTYPE html>
<html lang="en">
<style>
.parent{
border: 2px solid green;
height:30vh;
width:30vw;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
background-color: orange;
}
.child{
border: 2px solid red;
height:10vh;
width:10vw;
background-color: yellow;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">
This is the child element.
</div>
</div>
</body>
</html>
代码中,父元素是一个带有绿色边框的橙色框,其高度为视口高度的 30%,宽度为视口宽度的 30%。父元素借助"display: flex"、"flex-direction: row"、"justify-content: center"和"align-items: center"在水平和垂直方向上均居中。
要使用 align-items 和 justify-content,我们首先需要使用 display 属性将元素声明为弹性框。子元素是一个带有红色边框的黄色框,其高度为视口高度的 10%,宽度为视口宽度的 10%,位于父元素内部。
总结
在本文中,我们了解了如何使用 CSS 的 flexbox 属性将 <div> 居中。我们只需要使用 justify-content 和 flexbox 的 align-content 属性就可以实现同样的效果。
相关文章
有用资源
css 参考教程 - 该教程包含有关 css 的更多信息:https://www.cainiaomax.com/css/

