【问题标题】:CSS - How to center a div relative to a background image positioned as coverCSS - 如何使 div 相对于定位为封面的背景图像居中
【发布时间】:2016-03-04 08:28:36
【问题描述】:

我正在尝试使一个 div 相对于另一个 div 居中,该 div 将背景图像定位为封面。

html:

<div id="back">
  <div id="box">
    <p>test 1</p>
    <p>test 2</p>
    <p>test 3</p>
  </div>
</div>

css:

#back{
   position: absolute;
   top: 0;
   left: 0;
  right: 0;
  bottom: 0;
  background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/White_square_in_purple_background.svg/450px-White_square_in_purple_background.svg.png');
  background-repat: no-repeat;
  background-position: 50%;
  background-size: cover;
}

#box{
  position: absolute;
  top:10%;
  left: 20%;
  bottom: 10%;
  right: 20%;
  background: red;
}

这是一个小提琴:

http://jsfiddle.net/8x7tgrqm/

我试图在不同屏幕尺寸的背景中始终将红色 div 居中在白色框内。尝试调整窗口大小以了解我的意思。 我想知道在 CSS 甚至 JS 中是否有办法让框始终居中于背景白框。

谢谢

【问题讨论】:

  • 你想让红色完全覆盖白色吗?
  • 是或无论如何都尽可能多地填充白框。

标签: javascript jquery html css


【解决方案1】:

这是一个使用很棒的 vmax 单元的解决方案:

http://jsfiddle.net/x5m3w40o/2/

#box{
    position: absolute;
    top:50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width:57vmax;
    height:57vmax;
    background: red;
}  

在这种特殊情况下,您可能需要将 57 vmax 值调整为 58-59 以使其完全覆盖白色矩形。

【讨论】:

  • 比我即将发布的解决方案好得多
  • 非常感谢。我将它与矩形一起使用,但我遇到了一些问题,因为它不像 jsfiddle 那样像素完美,但我可以忍受,谢谢!!!
猜你喜欢
  • 2019-09-18
  • 1970-01-01
  • 1970-01-01
  • 2020-02-03
  • 2016-10-26
  • 2014-02-25
  • 1970-01-01
  • 1970-01-01
  • 2014-08-07
相关资源
最近更新 更多