【问题标题】:CSS - centered image over a DIV with responsive background and full height image display [duplicate]CSS - 在具有响应背景和全高图像显示的 DIV 上居中图像[重复]
【发布时间】:2015-08-14 10:04:31
【问题描述】:

如果您仔细阅读这个问题,您会注意到这不是重复的问题。这是关于具有全高图像显示的响应式背景上的图像。与其他问题相关的答案在这里毫无用处。感谢 jacob 的简单解决方案。

问题:

我有一个具有响应式背景的 DIV。我正在尝试在 DIV(或背景,如果您愿意)上放置一个居中的 png“徽标”。这就是我所拥有的:

.divWithBG {
    background-image: url(...);
    background-size: contain;
    background-repeat: no-repeat;
    width: 100%;
    height: 0;
    padding-top: 45.45%; /* (h/w) x 100 */
    margin-bottom: 30px;
}
.divWithBG img{
    display: block;
    margin: 0 auto;
}

¿我需要做什么才能将图像放入 div 中?垂直和水平居中。

非常感谢。

【问题讨论】:

  • 你可以使用 flex-box 吗?它使它变得非常容易。
  • 这不是重复的问题,凯文。它有一个区别:响应式背景(全图高度显示)
  • 为什么不直接将徽标添加为第二个背景图像?
  • 我会检查 flexbox,Jacob。它看起来既漂亮又简单。谢谢!
  • 作为第二个背景图像?雅各布是什么意思?我猜,第二个背景会继承相同的属性...

标签: html css image centering


【解决方案1】:

您可以简化并使用 2 张背景图片。 Multiple background images 在 CSS 中:

    .divWithBG {
        background-image: url("http://lorempizza.com/380/240") , url("http://lorempizza.com/2000/2000");
        background-size: 50%, contain;
        background-repeat: no-repeat, no-repeat;
        background-position:center;
        width: 100%;
        padding-top: 45.45%; /* (h/w) x 100 */
        margin-bottom: 30px;
    }
<div class="divWithBG"></div>

您想要置顶的背景图片首先出现在 background 属性中。

【讨论】:

  • 工作就像一个魅力,雅各布。谢谢,确实!
  • @Sergio 没问题,很高兴我能帮上忙!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-11
  • 2015-03-15
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-30
  • 2015-12-04
相关资源
最近更新 更多