html 响应式背景图片上的文字

html text on responsive background image

我想实现以下目标:

有背景图片,上面有文字的地方(文字位置是bootstrap offset-6 col-6)

并使其响应迅速。

问题是,与传统背景不同,我确实关心背景图像如何被截断,我需要 phone 无论宽度如何都可见。

我试过: background: url(background-photo.jpg) center center cover no-repeat fixed;

还有 How to get div height to auto-adjust to background size?

上的隐形 img 把戏

在所有情况下,phone 都会被截断

我们将不胜感激

编辑:
根据要求 - 原始 div 结构是:

<div id="hungry">
    <div class="col-xs-offset-6 col-xl-offset-6 col-xs-6 col-xl-6">
        <p>Hungry doesn't always happen in the kitchen</p>
    </div>
</div>

但我可以将其更改为任何有效...

您可以尝试调整 Bootstrap 3 中的超大屏幕 class,就像我对我的网站所做的那样。

.jumbotron {
    background: url('background-photo.jpg') no-repeat center center;
}

您可以根据需要更改超大屏幕的尺寸。

<div row jumbotron>
    <div class="col-md-6 col-md-offset-6">text</div>
</div>

JavaScript

的解决方案

我知道这不是我使用 JavaScript 的 CSS 解决方案,但它可以作为我们寻找 CSS 东西时的临时解决方案。

HTML 与您发布的相同:

<div id="hungry">
    <div class="col-xs-offset-6 col-xl-offset-6 col-xs-6 col-xl-6">
        <p>Hungry doesn't always happen in the kitchen</p>
    </div>
</div>

ID 为“hungry”的 div 的 CSS 将如下所示:

#hungry {
    background:url('http://i.stack.imgur.com/7xasp.jpg') no-repeat center center ;
    background-size:cover;
    width:100%;
}

最后,使用 JavaScript(我使用 jQuery 使其更容易),根据屏幕宽度调整 #hungry 的高度:

// you know the size for your image
imageWidth = 1919;
imageHeight = 761;
imageProportion = imageHeight/imageWidth;

function resizeJumbo() {
    $("#hungry").css({ height: $(window).width() * imageProportion });
}

$(window).on("resize", function() {
    resizeJumbo();
});

$(document).ready(function() {
    resizeJumbo();
});

您可以看到有关此 fiddle 的演示:http://jsfiddle.net/hyfz0Lga/

只有 CSS 的解决方案

稍微更新一下CSS饿了div:

#hungry {
    background:url('http://i.stack.imgur.com/7xasp.jpg') no-repeat center center ;
    background-size:cover;
    width:100%;
    padding-top:20%;
    padding-bottom:20%;
}

您可以在此处查看它的运行情况:http://jsfiddle.net/hyfz0Lga/1/

为什么 padding-top:20%padding-bottom:20%

这些值与图片的大小以及它们之间的比例有关。在你的例子中:宽度 = 1919 和高度 = 761,所以宽度和高度之间的比例是 (761 / 1919) * 100 = 39.65%。只需在顶部添加该值的一半,在底部添加该值的一半,那么文本将始终保持在中间,而图片将始终成比例。

我知道它有点“hacky”并且需要了解一些数据,但它似乎运行良好。