简体   繁体   English

将div缩放为背景图像的高度

[英]Scale div to background-image height

I've got a page using a background-image. 我有一个使用背景图片的页面。 background-size is set to cover . background-size设置为cover

The content is just a heading and two buttons. 内容只是一个标题和两个按钮。 I want the div to be always the proportional height fitting to the background. 我希望div始终是适合背景的比例高度。

What's the best way to do this (if possible with pure CSS)? 最好的方法是什么(如果可能,使用纯CSS)?

You can use one same image file for both background and inline, and set the inline image to visibility: hidden; 您可以将同一图像文件用于背景和内联,并将内联图像设置为visibility: hidden; (keep space), so the div can automatically resize based on the image size. (保留空间),因此div可以根据图像大小自动调整大小。

There is no way to detect the background image size with CSS. 无法使用CSS检测背景图像的大小。

 .container { background: url("https://picsum.photos/600/150?image=0") 0 0 no-repeat; background-size: cover; position: relative; border: 1px solid red; overflow: hidden; } .image { visibility: hidden; } .title { position: absolute; width: 100%; background: rgba(255, 255, 255, .5) } 
 <div class="container"> <div class="title">Hello</div> <img class="image" src="https://picsum.photos/600/150?image=0"> </div> 

know this is old thread but stumbled upon it. 知道这是旧线程,但偶然发现了它。

the following works for me if i know the dimensions of the image, 如果我知道图像的尺寸,以下内容对我有用,

eg. 例如。 1220x404 => 1220/404 = 3.01980198 = 30.1980198 1220x404 => 1220/404 = 3.01980198 = 30.1980198

header { max-height: 404px; height: 30.1980198vw; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM