我如何让一个div自动调整到背景的大小,我为它没有设置一个特定的高度(或最低高度)?
当前回答
我有这个问题,并找到了Hasanavi的答案,但我在宽屏上显示背景图像时遇到了一个小bug -背景图像没有扩散到屏幕的整个宽度。
所以这是我的解决方案-基于Hasanavi的代码,但更好…这应该适用于超宽屏幕和手机屏幕。
/*WIDE SCREEN SUPPORT*/
@media screen and (min-width: 769px) {
div {
background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
background-size: cover;
background-repeat: no-repeat;
width: 100%;
height: 0;
padding-top: 66.64%; /* (img-height / img-width * container-width) */
/* (853 / 1280 * 100) */
}
}
/*MOBILE SUPPORT*/
@media screen and (max-width: 768px) {
div {
background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
background-size: contain;
background-repeat: no-repeat;
width: 100%;
height: 0;
padding-top: 66.64%; /* (img-height / img-width * container-width) */
/* (853 / 1280 * 100) */
}
}
你可能已经注意到了,background-size: contains;属性不适合超宽屏幕,背景尺寸:覆盖;属性不适合移动屏幕,所以我使用这个@media属性来处理屏幕大小并修复这个问题。
其他回答
我敢肯定这东西在这里永远不会被看到。但如果你的问题和我一样,这就是我的解决方案
.imaged-container{
background-image:url('<%= asset_path("landing-page.png") %> ');
background-repeat: no-repeat;
background-size: 100%;
height: 65vw;
}
我想在图像的中心有一个div,这将允许我这样做。
在Umbraco CMS中有这个问题,在这种情况下,你可以使用div的'style'属性将图像添加到div:
style="background: url('@(image.mediaItem.Image.umbracoFile)') no-repeat scroll 0 0 transparent; height: @(image.mediaItem.Image.umbracoHeight)px"
如果它是一个单一的预定背景图像,你想要div在不扭曲背景图像的纵横比的情况下进行响应,你可以首先计算图像的纵横比,然后创建一个div,通过以下步骤保持它的纵横比:
假设你想要一个4/1的纵横比,div的宽度是32%:
div {
width: 32%;
padding-bottom: 8%;
}
这是因为填充是根据包含元素的宽度计算的。
我能想到的最好的解决办法是用百分比来指定你的宽度和高度。这将允许您根据显示器大小调整屏幕大小。它更响应式的布局。
举个例子。 你有
<br/>
<div> . //This you set the width percent to %100
<div> //This you set the width percent to any amount . if you put it by 50% , it will be half
</div>
</div>
这是最好的选择,如果你想要一个响应式布局,我不建议浮动,在某些情况下浮动是可以使用的。但在大多数情况下,我们避免使用float,因为当你进行跨浏览器测试时,它会影响很多事情。
希望这对你有所帮助。
有一个纯CSS的解决方案,其他的答案错过了。
“content:”属性主要用于在元素中插入文本内容,但也可以用于插入图像内容。
.my-div:before {
content: url("image.png");
}
这将导致div将其高度调整为图像的实际像素大小。要调整宽度,添加:
.my-div {
display: inline-block;
}