CSS教程
CSS进阶

如何在CSS中将按钮居中?

CSS主要用于为 HTML 网页。使用 CSS ,我们可以指定页面上元素的排列。
有多种方法可以将按钮对准网页中心。我们可以水平和垂直对齐按钮。我们可以使用以下方法将按钮居中:
text-align: center-通过将父div标签的text-align属性值设置为居中。 margin: auto-通过将margin属性的值设置为auto。 display: flex-通过将display属性的值设置为flex并将 justify-content 属性的值设置为 center display: grid-通过将显示属性的值设置为网格。
通过一些说明让我们理解上述方法。

示例

在此示例中,我们使用的是 text-align 属性并将其值设置为 center
在这里,我们将 text-align: center; 放置在元素的父div标签中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Center align button</title>
<style>
.container{
text-align: center;
border: 7px solid red;
width: 300px;
height: 200px;
padding-top: 100px;
}
#btn{
font-size: 25px;
}
</style>
</head>
<body>
<div class="container">
<button id ="btn"> Click me </button>
</div>
</body>
</html>
输出
如何居中CSS

示例

中的一个按钮在此示例中,我们使用 display: grid; 属性和 margin: auto ; 属性。在这里,我们将 display: grid; 放置在按钮元素的父div标签中。
按钮将放置在水平和垂直位置的中心。
<!DOCTYPE html>
<html>
<head>
<title>Center align button</title>
<style>
.container {
width: 300px;
height: 300px;
border: 5px solid red;
display: grid;
}
button {
background-color: lightblue;
color: black;
font-size: 25px;
margin: auto;
}
p{
font-size: 25px;
}
</style>
</head>
<body>
<div class="container">
<button> Click me </button>
</div>
<p>In this example we are using the <b> display: grid; </b> and <b> margin: auto;</b> properties</p>
</body>
</html>
输出
如何居中CSS

示例

中的一个按钮,这是将按钮置于中心的另一个示例。在此示例中,我们使用 display: flex; 属性, justify-content: center; 属性和 align-items: center; 属性。
此示例将帮助我们将按钮放置在水平和垂直位置的中心。
<!DOCTYPE html>
<html>
<head>
<title>Center align button</title>
<style>
.container {
width: 300px;
height: 300px;
border: 5px solid red;
display: flex;
justify-content: center;
align-items: center;
}
button {
background-color: lightblue;
color: black;
font-size: 25px;
}
</style>
</head>
<body>
<div class="container">
<button> Click me </button>
</div>
</body>
</html>
输出
如何居中CSS中的按钮
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4