【问题标题】:Center div in middle of backround image across all screen resolutions在所有屏幕分辨率的背景图像中间居中 div
【发布时间】:2017-01-04 14:04:36
【问题描述】:

我正在使用这段代码来显示一个背景图像,它占据了浏览器的整个垂直高度。

<div id="outer"></div>

CSS

#outer {
  background-image: url(https://www.mydomain./image.jpg);
  height: 100vh;
  background-size: cover;
  background-repeat: no-repeat;
}

我希望在其中放置一个 div,它在所有屏幕分辨率的图像中间垂直和水平居中。

到目前为止,我尝试的一切都没有成功。这需要大多数浏览器支持。

【问题讨论】:

标签: html css


【解决方案1】:

选项 1:Position Absolute 和 translate -50% 方法

body {
  margin: 0; padding: 0;
}
.outer {
  position: relative;
  background-image:url(http://i.imgur.com/55PnNyJ.jpg);
  height:100vh;
  background-size: cover;
  background-repeat: no-repeat;
}
.centered {
  position: absolute;
  top: 50%; left: 50%;
  transform: translateY(-50%) translateX(-50%);
  display: inline-block;
  color: hsla(0, 0%, 100%, 0.4);
  background-color: hsla(0, 0%, 0%, 0.4);
}
<div class="outer">
  <div class="centered">I'm (almost) On A Boat</div>
</div>

小提琴

https://jsfiddle.net/Hastig/j7rgjspt/2/


选项 2:Flexbox 和 justify-content/align-items center

body {
  margin: 0; padding: 0;
}
.outer {
  display: flex;
  justify-content: center;
  align-items: center;
  background-image:url(http://i.imgur.com/55PnNyJ.jpg);
  height:100vh;
  background-size: cover;
  background-repeat: no-repeat;
}
.centered {
  display: inline-flex;
  text-align: center;
  color: hsla(0, 0%, 100%, 0.4);
  background-color: hsla(0, 0%, 0%, 0.4);
}
<div class="outer">
  <div class="centered">I'm (almost) On A Boat</div>
</div>

小提琴

https://jsfiddle.net/Hastig/j7rgjspt/1/

【讨论】:

    【解决方案2】:

    为内部div设置heightwidth,然后使用margin: auto使其水平居中,padding: calc(50vh - 10px) 0垂直居中。 10px 必须是内部div 高度的一半。试试这个:

    #outer {
      background-image: url('http://placehold.it/100x100');
      height: 100vh;
      background-size: cover;
      background-repeat: no-repeat;
    }
    #inner {
      color: red;
      width: 100px;
      height: 20px;
      margin: auto;
      text-align: center;
      padding: calc(50vh - 10px) 0;
    }
    <div id="outer">
      <div id="inner">test</div>
    </div>

    【讨论】:

    • 这是最简单也是最值得注意的解决方案。谢谢!
    猜你喜欢
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多