如何使用 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>

更新于:2023年11月16日

浏览量 1K+

启动您的 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.