【问题标题】:How do to center a div over a div [duplicate]如何将 div 居中在 div 上 [重复]
【发布时间】:2018-06-06 04:48:53
【问题描述】:

这就是我想要达到的目标。我尝试使用绝对位置,它似乎适用于一种屏幕尺寸,但不适用于其他屏幕尺寸。

.countdown {
  width: 200px;
  background: #b02d1b;
  margin: 0;
  border-radius: 5px;
  color: #fff;
  text-align: center;
  padding: 5px;
  position: absolute;
  z-index: 1;
}

.countdown-bg {
  width: 100%;
  border-top: solid 1px #ccc;
  position: absolute;
  margin: 12px;
}
<div class="countdown"> Final Hours </div>
<div class="countdown-bg"></div>

【问题讨论】:

  • 发布html和css代码
  • 使用 text-align:center 水平居中,并将相对顶部定位到直线上方。
  • 你需要发布你的代码
  • 我们需要查看您的代码,有多种方法可以完成此操作
  • 正如其他人所提到的,我们无法在不查看您的代码的情况下解决您的确切情况。你可以创建一个Minimal, Complete, and Verifiable example

标签: html css


【解决方案1】:

我想我对你的问题有一个解决方案:

.divOuter {
  background-color: #cccccc;
  width: 100%;
  height: 2px;
  position: absolute;
}

.divInner {
  background-color: #cc0000;
  width: 130px;
  height: 20px;
  position: relative;
  top: -12px;
  margin: 0 auto;
  color: #ffffff;
  text-align: center;
  font-family: Verdana;
  font-size: 0.8em;
  font-weight: bold;
  border-radius: 10px;
  border: 4px solid #ffffff;
}
<div class="divOuter">
  <div class="divInner">FINAL HOURS!</div>
</div>

简要说明:

我们有两个 div,html 中的第二个在第一个之上。 CSS 中的这个位置称为 float

当我们需要这种效果时,我们会使用 CSS 的“位置”属性以及 AbsotuleRelative 等值。

在这种情况下,第一个 Div 构成细线,第二个 Div 构成红色矩形。

css 的“top”、“left”、“right”和“button”属性导致第二个 Div 相对于第一个 Div 对齐。并且属性 "margin: auto" 使内部 div 与外部 div 的中心对齐。

希望能帮到你!

【讨论】:

  • 谢谢,丹尼斯。它奏效了。
【解决方案2】:

没有弹性盒

将一个 div 包裹在另一个 div 中。制作外部 div position: relative 和内部 div position: absolute。使用lefttransform 将内部div 居中

.countdown {
  position: relative;
  border-top: solid 1px #ccc;
  margin: 15px 0;
}

.countdown>.content {
  width: 200px;
  text-align: center;
  background: #b02d1b;
  border-radius: 5px;
  color: #fff;
  padding: 5px;
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1;
  text-transform: uppercase;
}
<div class="countdown">
  <div class="content">Final Hours!</div>
</div>

带弹性盒

使用 flexbox 的好处是不用设置位置,可以用justify-content居中。

.countdown {
  border-top: solid 1px #ccc;
  margin: 15px 0;
  display: flex;
  justify-content: center;
}

.countdown>.content {
  width: 200px;
  text-align: center;
  background: #b02d1b;
  border-radius: 5px;
  color: #fff;
  padding: 5px;
  transform: translateY(-50%);
  z-index: 1;
  text-transform: uppercase;
}
<div class="countdown">
  <div class="content">Final Hours!</div>
</div>

【讨论】:

    猜你喜欢
    • 2017-09-25
    • 2013-02-27
    • 2023-04-09
    • 2017-02-28
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    相关资源
    最近更新 更多