如何使用 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` 属性用于设置弹性盒中弹性项目的默认对齐方式。它垂直对齐项目。
CSS `align-items` 属性的语法如下:
Selector {
display: flex;
justify-content: /*value*/
}
以下是其值:
stretch - 弹性项目被拉伸以适应容器。
center - 弹性项目位于容器的中心。
flex-start - 弹性项目位于容器的开头。
flex-end - 弹性项目位于容器的结尾。
创建按钮
<button> 元素用于在网页上创建一个按钮。
<button>This button is centered</button>
设置按钮样式:
button{
font-size: 18px;
border: none;
padding:10px;
background-color: darkblue;
color:white;
}
将按钮放在 div 内
要使按钮居中对齐,请将按钮元素放在 div 内。
<div class="centered"> <button>This button is centered</button> </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);
}
button{
font-size: 18px;
border: none;
padding:10px;
background-color: darkblue;
color:white;
}
</style>
</head>
<body>
<h1>Centering Example</h1>
<div class="centered">
<button>This button is centered</button>
</div>
</body>
</html>
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP