创建 HTML

  • 创建两个 <div> 元素并向内框添加内容。
  • 使用 <br> 标签添加换行符。
<body>
  <div class="outer">
    <div class="inner">
      居中的文本
      <br/>不受文本的高度,宽度影响
    </div>
  </div>
</body>
如何在 Div 中将绝对定位的元素居中

在 CSS 中,将绝对定位的元素居中会导致一些困难。

如果元素的宽度未知,则可能会特别复杂。

下面,我们将讨论已知宽度和未知宽度的两种情况。

首先,我们将一个绝对定位的元素居中,其尺寸未知。

添加 CSS

将“外部”类的位置设置为“相对”,将“内部”类的位置设置为“绝对”。

.outer {
  position: relative;
  margin: 5%;
  width: 80%;
  height: 500px;
  border: 2px solid #1703fc;
}
.inner {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  max-width: 50%;
  text-align: center;
  border: 2px solid #468a4d;
}

这是完整的代码:

将具有未知尺寸的绝对定位元素居中的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      .outer {
        position: relative;
        margin: 5%;
        width: 80%;
        height: 500px;
        border: 2px solid #1703fc;
      }
      .inner {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        max-width: 50%;
        text-align: center;
        border: 2px solid #468a4d;
      }
    </style>
  </head>
  <body>
    <div class="outer">
      <div class="inner">居中的文本
        <br/>居中不受文本的长度,宽度,高度的影响</div>
    </div>
  </body>
</html>

在上面的例子中, left 属性是相对于父元素的,而变换是相对于其父元素的宽度/高度的。

因此,我们可以在子元素和父元素上拥有一个具有灵活宽度的居中元素。

接下来,我们将展示一个将绝对定位元素居中的示例,该元素具有精确的尺寸。
其中无论外部元素的宽度如何,内部框都将保持居中。

将具有固定尺寸的绝对定位元素居中的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      .outer {
        position: relative;
        width: 40%;
        height: 120px;
        margin: 20px auto;
        border: 2px solid #468a4d;
      }
      .inner {
        position: absolute;
        width: 100px;
        height: 100px;
        top: 10px;
        left: 50%;
        margin-left: -50px;
        background-color: #1703fc;
      }
    </style>
  </head>
  <body>
    <div class="outer">
      <div class="inner"></div>
    </div>
  </body>
</html>
日期:2020-06-02 22:14:58 来源:oir作者:oir