添加 CSS

现在,让我们看看如何通过以下步骤将“small-box”id 置于“bix-box”id 中。

  • 设置两个框的宽度和高度属性。

另外,指定它们的背景颜色。

  • 将“big-box”的显示设置为“flex”并添加 align-items 属性以指定 flex 容器内内容的垂直对齐方式。

还可以使用 -webkit- 扩展名。

  • 将“big-box”的 justify-content 属性设置为“center”以水平对齐内容。
#big-box {
  width: 200px;
  height: 200px;
  background-color: #666666;
  display: flex;
  align-items: center;
  justify-content: center;
  -webkit-align-items: center;
}
#small-box {
  width: 100px;
  height: 100px;
  background-color: #8ebf42;
}

使用 Flexbox 将内容居中的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      #big-box {
        width: 200px;
        height: 200px;
        background-color: #666666;
        display: flex;
        align-items: center;
        justify-content: center;
        -webkit-align-items: center;
      }
      #small-box {
        width: 100px;
        height: 100px;
        background-color: #8ebf42;
      }
    </style>
  </head>
  <body>
    <h2>Centering Content</h2>
    <div id="big-box">
      <div id="small-box"></div>
    </div>
  </body>
</html>

-Webkit- 扩展与 Safari、Google Chrome 和 Opera(较新版本)的 align-items 属性一起使用。

让我们看另一个示例,即使文本更改为使其更宽或者更高,该框仍将保持居中。

使用 Flexbox 居中内容的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      .flexbox-container {
        background: #cccccc;
        display: flex;
        align-items: center;
        -webkit-align-items: center;
        justify-content: center;
        height: auto;
        margin: 0;
        min-height: 500px;
      }
      .flexbox-item {
        max-height: 50%;
        background: #666666;
        font-size: 15px;
      }
      .fixed {
        flex: none;
        max-width: 50%;
      }
      .box {
        width: 100%;
        padding: 1em;
        background: #1c87c9;
      }
    </style>
  </head>
  <body>
    <h2>Centering Content</h2>
    <div class="flexbox-container">
      <div class="flexbox-item fixed">
        <div class="box">
          <h2>Centered by Flexbox</h2>
          <p contenteditable="true">此框垂直居中和水平居中。 </p>
        </div>
      </div>
    </div>
  </body>
</html>

创建 HTML

  • 创建一个 id 为“big-box”的 <div> 元素,然后在第一个元素中放置另一个 id 为“small-box”的 <div> 元素。
<h2>Centering Content</h2>
<div id="big-box">
  <div id="small-box"></div>
</div>
如何使用 Flexbox 将内容垂直和水平居中

开发人员可以确保居中内容是 CSS 布局中最难做的事情之一。
CSS Flexbox 现在允许我们对 HTML 元素对齐有更多的控制,包括居中你想要的一切。

下面,我们将演示如何轻松地将内容垂直和水平居中。

日期:2020-06-02 22:14:59 来源:oir作者:oir