背景图像没有覆盖,文本垂直对齐底部

时间:2015-01-22 10:07:44

标签: html css background-image

我很难理解如何实现一些目标。我创建了一个带背景图像的div,背景图像需要响应并覆盖背景区域。文本也需要垂直对齐div的底部。

我将其中四个并排坐在一起,各占25%。

我已经创建了它的演示,并寻找一些建议来解决这个问题。

.img1{
        height: 400px;
        width: 25%;
        box-sizing: border-box;
        padding: 40px 30px; 
        @include background-size(cover);
        text-align: center; 
        float: left;    
        background-size: cover;
        background:linear-gradient(to top, rgba(0,0,0,0.8) 0%,rgba(0,0,0,0) 30%), url("http://upload.wikimedia.org/wikipedia/commons/2/28/Most_beautiful_landscape_wallpaper.jpg");
    }

Demo of my problem

3 个答案:

答案 0 :(得分:0)

background-size

之后声明您的background

<强> demo

background:linear-gradient(to top, rgba(0,0,0,0.8) 0%,rgba(0,0,0,0) 30%), url("http://upload.wikimedia.org/wikipedia/commons/2/28/Most_beautiful_landscape_wallpaper.jpg");
background-size: cover;

注意:您可以在背景声明中添加center center以获得更好的效果。

要垂直对齐,您可以使用此技巧:在容器上添加:before,并使用display: inline-block使其h2。然后使用vertical-align: bottom

.img1 {
    font-size: 0; // make sure there is no space between inline-block elements
}
.img1:before {
    height: 100%;
    content: '';
    display: inline-block;
}
h2 {
    display: inline-block;
    vertical-align: bottom;
    font-size: 24px; // set the font size back for the title
}

<强> demo

如果您想要查看整个图像并且容器的高度自动适应,您还可以使用<img>元素:

<强> demo

答案 1 :(得分:0)

将此添加到CSS:

.img1 h2 {
margin-top: 300px;
}

答案 2 :(得分:0)

试试这个:

HTML:

<div class="img1">
    <h2>Family travel...</h2>
</div>

CSS:

.img1 {
float: left;
padding: 40px 30px;
width: 25%;
height: 400px;
box-sizing: border-box;
@include background-size(cover);
background-size: contain;
background: linear-gradient(to top, rgba(0,0,0,0.8) 0%,rgba(0,0,0,0) 30%), url("http://upload.wikimedia.org/wikipedia/commons/2/28/Most_beautiful_landscape_wallpaper.jpg");
}

.img1 h2 { 
position: relative;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
font-family: Tahoma, Helvetica, sans-serif;
font-size: 16px;
color: #fff; }

这是fiddle

问候,米兰。

相关问题