将div缩放为背景图像高度 [英] Scale div to background-image height

查看:99
本文介绍了将div缩放为背景图像高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用背景图片的网页。
background-size 设置为 cover



内容只是一个标题和两个按钮。
我希望div总是适合背景的比例高度。



最好的方法是什么(如果可能用纯CSS)?

解决方案

您可以将相同的图像(用于背景)放入 visibility:hidden; code>,所以div可以自动拉伸高度适合但不显示它。因为没有办法用CSS检测大小。



  .box {background:url(http://lorempixel.com/200 / 100 /)无重复; background-size:cover;位置:相对; border:1px solid red;}。box> img(visibility:hidden;}。box> div {position:absolute; width:100%;背景:rgba(255,255,255,.5)}  

  div class =box> < div> Hello< / div> < img src =http://lorempixel.com/200/100//>< / div>  

/ p>

I've got a page using a background-image. background-size is set to cover.

The content is just a heading and two buttons. I want the div to be always the proportional height fitting to the background.

What's the best way to do this (if possible with pure CSS)?

解决方案

You could put the same image (for background) into the markup with visibility: hidden;, so the div can automatically stretch the height to fit but without display it. As there is no way to detect the size with CSS.

.box {
    background: url("http://lorempixel.com/200/100/") no-repeat;
    background-size: cover;
    position: relative;
    border: 1px solid red;
}
.box > img {
    visibility: hidden;
}
.box > div {
    position: absolute;
    width: 100%;
    background: rgba(255,255,255, .5)
}

<div class="box">
    <div>Hello</div>
    <img src="http://lorempixel.com/200/100/"/>
</div>

这篇关于将div缩放为背景图像高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆