4

简单的概念,我想要一个响应式 CSS 背景图像,在浏览器窗口中以 1:1 的宽度/高度比缩放,这是简单的部分

body{
    height:100%;
}

.banner{
    height:100%;
    background: url('path/to/img') center center no-repeat;
    background-size:contain;
}

<body>
    <div class="banner"></div>
</body>

问题是我还想将文本放置在带有自动换行的背景容器中,并在浏览器窗口调整大小时使背景图像的高度与文本高度一致。

<body>
    <div class="banner">
        <p>
            Lorem ipsum dolor sit amet, in eos idque epicuri...
        </p>
    </div>
</body>

纯 CSS/HTML 可以做到这一点吗?

4

4 回答 4

19

背景图片

做背景的一种方法是background-size: cover按照这篇文章使用:

html { 
  background: url(images/bg.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

文本

要编写文本,您可以查看使用@media查询,但是当您选择了答案后,剩下的就交给你们了 :)

于 2013-11-02T20:06:07.333 回答
4

尝试这个:

HTML:

<div class="banner">
    <img src="https://www.google.es/images/srpr/logo11w.png" />
    <div class="content">
        Content
    </div>
</div>

CSS:

.banner {
    position: relative;
}
.banner > img{
    width: 100%;
    height: auto;
}
.banner > .content{
    position: absolute;
    top: 0;
    bottom: 0;
    overflow: auto;
}

演示

于 2013-11-02T19:54:17.587 回答
1

根据答案,对于任何有兴趣的人来说,要按比例缩放 CSS 背景图像与文本换行,以下应该在大多数情况下都有效。

小提琴

首先,为了确保背景图像的渲染不会大于移动分辨率,我添加了一个视口

@media screen and (max-width: 800px){
    .viewport {
        position:absolute;
        right:0;
        left:0;
        top:0;
        bottom:0;
        overflow-x:hidden;
        overflow-y:scroll;
    }
}

<html>
<body>
    <div class="viewport">
        <!-- background image -->
    </div>
</body>
<html>

然后我在背景元素上background-size:cover;使用了高度为 的属性,auto以允许它在移动设备上随文本换行一起流动。为了允许背景元素的高度相对于文本换行重新调整大小,其父元素(在本例中为body)的高度必须为100%.

html,body{
    height:100%;
}

.banner{
    background: url('path/to/banner.jpg') center center no-repeat;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

@media screen and (max-width: 800px){
    .viewport {
        position:absolute;
        right:0;
        left:0;
        top:0;
        bottom:0;
        overflow-x:hidden;
        overflow-y:scroll;
    }

    .banner{
        height:auto;
    }

    .banner .banner-container {
        position:relative;
        overflow:hidden;
    }
}

<html>
<body>
    <div class="viewport">
        <div class="banner">
            <div class="banner-container">
                <h1>Lorem ipsum dolor sit amet, est intellegebat definitionem at</h1>
                <h1>Lorem ipsum dolor sit amet, est intellegebat definitionem at</h1>
                <h1>Lorem ipsum dolor sit amet, est intellegebat definitionem at</h1>
            </div>
        </div>
    </div>
</body>
<html>
于 2013-11-02T21:41:49.433 回答
0

我认为它可以帮助你 http://www.positioniseverything.net/easyclearing.html。我通过清除解决了我的问题。

于 2013-11-02T19:58:01.980 回答