【问题标题】:How to center div vertically in other div [duplicate]如何在其他div中垂直居中div [重复]
【发布时间】:2023-04-09 12:39:01
【问题描述】:

在我的代码中,我有一个带有背景图像的部分元素,我想在上面放置一个 div 元素,例如 this

但我不知道如何将该文本放在图像上。它只是粘在上面: 这是我的html和css:

* {
  background-color: black;
  font-family: Helvetica;
  color: seashell;
  opacity: 0.9;
  font-size: 22px;
  
}

#mission {
  margin: 0 auto;
  width: 1200px;
  height: 700px;
  background-image: url(https://content.codecademy.com/courses/freelance-1/unit-4/img-mission-background.jpg);
  background-repeat: no-repeat;
}

#mission div {
  background-color: black;
  text-align: center;
  
}
<section id="mission">
  <div>
    <h2>Our Mission</h2>
    <h4>Handpicked, Artisanally Curated, Free Range, Sustainable, Small Batch, Fair Trade, Organic Tea</h4>
  </div>
 </section>

【问题讨论】:

  • 唯一的方法是使用flexbox。当您不知道元素的高度时,这也有效。它是supported by all modern browsers,甚至是 Internet Explorer。
  • @Pieterjan 我不知道你是什么意思。我应该将display: flex; 分配给&lt;section&gt; 吗?
  • 通常是的。 display:flex;flex-direction:column;justify-content:center;
  • 2021,我们很多都没有头绪,不用担心。

标签: html css


【解决方案1】:

HTML:

<div class='parent'>
    <div class='child'></div>
</div>

CSS:

.parent {
    display: flex;
    align-items: center;
    justify-content: center;
}

【讨论】:

    【解决方案2】:

    你需要使文本位置:相对

    * {
      background-color: black;
      font-family: Helvetica;
      color: seashell;
      opacity: 0.9;
      font-size: 22px;
      
    }
    
    #mission {
      margin: 0 auto;
      width: 1200px;
      height: 700px;
      background-image: url(https://content.codecademy.com/courses/freelance-1/unit-4/img-mission-background.jpg);
      background-repeat: no-repeat;
    }
    
    #mission div {
      background-color: black;
      text-align: center;
    
    }
    .text { position: relative; top: 310px} /* or use calc() to find better placement */
    <section id="mission">
      <div class="text">
        <h2>Our Mission</h2>
        <h4>Handpicked, Artisanally Curated, Free Range, Sustainable, Small Batch, Fair Trade, Organic Tea</h4>
      </div>
     </section>

    【讨论】:

    • 您好,感谢您的回答。它解决了我的问题..部分。我不知道为什么,但不知何故,现在图像不再出现,只有一个黑色背景。我检查了一下,它不是来自 div 元素。你知道我该如何解决这个问题吗?
    • 正如你在 sn-p 中看到的,它在这里工作。所以也许我正在使用一个你用来做其他事情的类
    【解决方案3】:

    只需使用引导程序 如果您还没有使用过,请谷歌如何使用引导程序。

    所以对于我们在 div 上调用 class="my-auto" 的答案

    【讨论】:

    • 这需要明确定义孩子的身高
    • 是的,没错
    猜你喜欢
    • 2017-09-25
    • 2014-02-15
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 2015-10-10
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多