如何使用 CSS 的 Flexbox 属性居中一个 <div>?
要使用 CSS 的 flexbox 属性居中一个 div,我们将使用 CSS flexbox 及其属性。在本文中,我们将了解并执行以下三件事,以使用 CSS 的 Flexbox 属性居中一个 <div>
使用 flexbox 在水平轴上居中 div
要在水平轴上居中 div,我们将使用 CSS justify-content 属性,该属性可水平居中 div。
示例
这是一个在水平轴上居中 div 的示例。
<html>
<head>
<title>
Center a div using flex property
</title>
<style>
.container {
display: flex;
justify-content: center;
}
.item {
border: 2px solid green;
width: 100px;
height: 100px;
background-color: rgb(109, 224, 244);
}
</style>
</head>
<body>
<h3>
Center div Using flexbox on Horizontal Axis
</h3>
<p>
We have used <strong>justify-content</strong>
property to center the item horizontally.
</p>
<div class="container">
<p class="item"></p>
</div>
</body>
</html>
使用 flexbox 在两个轴上居中 div
要使用 flexbox 在两个轴上居中 div,我们使用了 CSS justify-content 和 align-items 属性。
- 我们使用了 "display: flex;" 来创建一个灵活的容器。
- 我们使用了 "justify-content: center;" 来水平居中 div。
- 我们使用了 CSS height 属性来设置 div 的高度,并使用了 "align-items: center;" 来垂直居中 div。
示例
<html>
<head>
<title>
Center a div using flex property
</title>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.item {
border: 2px solid green;
width: 100px;
height: 100px;
background-color: rgb(109, 224, 244);
}
</style>
</head>
<body>
<h3>
Center div Using flexbox on both Axes
</h3>
<p>
We have used <strong>justify-content</strong>
to center the item horizontally and
<strong>align-items</strong> to center the
flex item vertically.
</p>
<div class="container">
<p class="item"></p>
</div>
</body>
</html>
使用 Flexbox 居中多个项目
在本节中,我们将使用 flexbox 居中多个 flex 项目。为此,我们使用了 CSS flex-direction 属性,该属性根据指定的值显示 flex 项目。
- 为了对齐多个项目,我们使用了 "flex-direction: column;" 属性,该属性垂直显示 flex 项目。
- 我们居中了多个 flex 项目,并使用 flex-direction: column 将其垂直显示。还可以使用 flex-direction 的其他属性值,例如 **row**、**row-reverse** 和 **column-reverse**。
示例
这是一个使用 flexbox 居中多个项目的示例。
<html>
<head>
<title>
Center a div using CSS properties
</title>
<style>
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
}
.item {
padding:10px;
background-color: #04af2f;
color: white;
margin: 2px;
text-align: center;
letter-spacing: 1px;
border: 1px solid black;
}
</style>
</head>
<body>
<h3>
Center Multiple Items Using flex Property.
</h3>
<p>
We have used <strong>flex-direction</strong>
property to display items vertically.
</p>
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
</body>
</html>
结论
使用 CSS 居中 div 是一项重要的任务,这是一个非常简单的过程,可以使用各种 CSS 属性来实现。在本文中,我们使用了 CSS flexbox 来居中 div。我们执行了以下三件事:使用 CSS **justify-content** 属性在水平轴上居中 div,使用 **justify-content** 和 **align-items** 属性在两个轴上居中 div,以及使用 flexbox 居中多个 flex 项目。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP