简体   繁体   English

将div的大小设置为其背景图像

[英]Set size of the div to its background image

I have the following div on my page: 我的页面上有以下div:

<div id="logo">
</div>

I would like to put a background image in this div: 我想在此div中放入背景图片:

#logo {
    background: url('logo3_light.jpg') no-repeat;
    width: 100%;
    height: auto;
}

But the image never shows up, because the height of the div is 0px. 但是图像永远不会显示,因为div的高度为0px。

I would like somehow to set the height of the wrapping div to the height of the scaled image. 我想以某种方式将包装div的高度设置为缩放图像的高度。 Is it possible? 可能吗?

Since your original image is 1600x100 the height is 6.25% of its width, so you could try this 由于您的原始图片为1600x100因此高度为其宽度的6.25% ,因此您可以尝试

#logo {
    background: url(http://dummyimage.com/1600x100/000/fff.jpg) no-repeat;
    width: 100%;
    height: auto;
    padding-bottom : 6.25%; 
    background-size: cover; 
}

Example on codepen: http://codepen.io/anon/pen/EnJvI 有关代码笔的示例: http ://codepen.io/anon/pen/EnJvI


Note: you can't simply use height: 6.25% because the height would be relative to the height of the parent element (the body element, whose height is not defined and it is 0 , since your logo element is empty). 注意:您不能简单地使用height: 6.25%因为高度将对于父元素的高度( body元素,其高度未定义且为0 ,因为您的徽标元素为空)。

The padding-bottom use instead the width of the element itself to calculate the correct value (this technique is often used to keep the correct aspect ratio of videos on responsive design, fyi). padding-bottom使用元素本身的宽度来计算正确的值(此技术通常用于在响应式设计fyi上保持视频的正确长宽比)。

Anyway, I don't recommend to use empty markup for styling purpose: your logo should be a regular img element rather than a background, since a logo usually conveys information 无论如何,我不建议使用空标记来进行样式设置:您的徽标应该是常规的img元素而不是背景,因为徽标通常可以传达信息

Answer as found here: How to get div height to auto-adjust to background size? 在这里找到答案: 如何获取div高度以自动调整为背景大小?

<div style="background-image: url(http://your-image.jpg);">
    <img src="http://your-image.jpg" style="visibility:hidden"/>
</div>

Unfortunately, there is no easy way. 不幸的是,没有简单的方法。 You could for example using javascript get url of the image, load it and get its dimensions, then set the dimensions to the div element. 例如,您可以使用javascript获取图像的url,加载图像并获取尺寸,然后将尺寸设置为div元素。

What I would do, would, be just directly use tag to put image in the div. 我要做的就是直接使用标记将图像放入div中。 If you need additional content, you could put the content in another div inside the div you already have. 如果需要其他内容,可以将内容放在现有div内的另一个div中。 Then the internal divs positioning can be set to absolute etc etc, hope it gives you idea how to do it 然后可以将内部div的位置设置为绝对等,希望它能让您知道如何操作

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

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