如何使用 CSS 将元素垂直和水平居中?
要使用 CSS 将元素垂直和水平居中,可以使用 **justify-content** 和 **align-items** 属性。在我们的示例中,我们使用了 flex。
justify-content 属性
在 CSS 中,justify-content 属性用于水平对齐项目。CSS justify-content 属性的语法如下:
Selector {
display: flex;
justify-content: /*value*/
}
以下是属性值:
**flex-start** - 弹性项目放置在容器的开头。这是默认值。
**flex-end** - 弹性项目放置在容器的末尾
**center** - 弹性项目放置在容器的中心
**space-between** - 弹性项目之间会有间距
**space-around** - 弹性项目前后以及之间会有间距
**space-evenly** - 弹性项目周围会有相等的间距
align-items 属性
在 CSS 中,align-items 属性用于设置 flexbox 中 flex-items 的默认对齐方式。它垂直对齐项目。
语法
CSS align-items 属性的语法如下:
Selector {
display: flex;
justify-content: /*value*/
}
以下是属性值:
**stretch** - 弹性项目拉伸以适应容器
**center** - 弹性项目放置在容器的中心
**flex-start** - 弹性项目放置在容器的开头
**flex-end** - 弹性项目放置在容器的末尾
创建元素
假设我们要对齐一个 <h2> 元素。<h2> 元素用于在网页上创建标题:
<h2>This text is centered vertically and horizontally both</h2>
将元素设置在 div 内部
要水平居中对齐按钮,请将按钮元素设置在 div 内部:
<div class="centered"> <h2>This text is centered vertically and horizontally both</h2> </div>
设置 div 的样式并居中对齐
要垂直居中对齐,请使用 **align-items** 属性。要水平居中对齐,请使用 **justify-content** 属性。将两个值的属性值都设置为 center:
.centered {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid rgb(0, 70, 128);
}
示例
让我们看看示例
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.centered {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid rgb(0, 70, 128);
}
</style>
</head>
<body>
<h1>Centering Example</h1>
<div class="centered">
<h2>This text is centered vertically and horizontally both</h2>
</div>
</body>
</html>
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP