添加 CSS

  • 将 top 和 left 属性设置为 50% 以将 <div> 的左上角居中。
  • 将 margin-top 和 margin-left 属性设置为 <div> 高度和宽度的负一半。
.container {
  position: fixed;
  width: 500px;
  height: 200px;
  padding: 10px;
  border: 3px solid #147d43;
  background-color: #d4fce6;
  top: 50%;
  left: 50%;
  margin-top: -100px;  /* Negative half of height. */
  margin-left: -250px;  /* Negative half of width. */
}

这是我们代码的结果。

以固定位置居中元素的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      .container {
        position: fixed;
        width: 500px;
        height: 200px;
        padding: 10px;
        border: 3px solid #147d43;
        background-color: #d4fce6;
        top: 50%;
        left: 50%;
        margin-top: -100px;/* Negative half of height. */
        margin-left: -250px;/* Negative half of width. */
      }
    </style>
  </head>
  <body>
    <div class="container">
      以固定位置居中元素的示例。
    </div>
  </body>
</html>

如果我们不知道元素的大小,可以使用设置为“翻译”的转换属性。

使用 transform 属性将具有固定位置的元素居中的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      .container {
        position: fixed;
        width: 500px;
        height: 200px;
        padding: 10px;
        border: 3px solid #147d43;
        background-color: #d4fce6;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    </style>
  </head>
  <body>
    <div class="container">
      以固定位置居中元素的示例
    </div>
  </body>
</html>
如何以固定位置居中元素

有时,我们可能难以将位置设置为“固定”的元素居中。

让我们开始寻找解决方案吧!

首先,我们将展示一个我们知道元素大小的示例。

创建 HTML

  • 使用类名为“容器”的 <div> 元素。
<div class="container">
  以固定位置居中元素的示例。
</div>
日期:2020-06-02 22:14:58 来源:oir作者:oir