我如何让一个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属性来处理屏幕大小并修复这个问题。
其他回答
如果你可以在Photoshop中制作一张图像,其中主图层的不透明度为1左右,基本上是透明的,将img放在div中,然后将真实的图片作为背景图像。然后设置img的不透明度为1,并添加你想要的尺寸。
这张图片就是这样做的,你甚至不能把不可见的图像拖出页面,这很酷。
你可以这样做
<div style="background-image: url(http://your-image.jpg); position:relative;">
<img src="http://your-image.jpg" style="opacity: 0;" />
<div style="position: absolute;top: 0;width: 100%;height: 100%;">my content goes here</div>
</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"
这招对我很管用:
background-image: url("/assets/image_complete_path");
background-position: center; /* Center the image */
background-repeat: no-repeat; /* Do not repeat the image */
background-size: cover;
height: 100%;
这可能会有帮助,这不是一个确切的背景,但你明白这个简单的想法吗
<style>
div {
float: left;
position: relative;
}
div img {
position: relative;
}
div div {
position: absolute;
top:0;
left:0;
}
</style>
<div>
<img src="http://www.planwallpaper.com/static/images/recycled_texture_background_by_sandeep_m-d6aeau9_PZ9chud.jpg" />
<div>Hello</div>
</div>
推荐文章
- 在网页上用鼠标模拟震颤(例如帕金森病)?
- Bootstrap抛出Uncaught错误:Bootstrap的JavaScript需要jQuery
- 如何改变文本区域的边框颜色:焦点
- 我如何设置背景颜色为文本的宽度,而不是整个元素的宽度,使用CSS?
- 如何删除和清除所有的本地存储数据
- 设备像素比到底是什么?
- 我如何做一个半透明的背景?
- 强制打开“另存为…”弹出打开文本链接点击PDF在HTML
- 如何修改标签文本?
- 在CSS网格布局中等高行
- $(window).width()与媒体查询不一样
- 在HTML中还有其他有用的空格码吗,比如半空格的 , em-spaces, en-spaces等等?
- 输入触发器按钮单击
- 如何以及在哪里使用::ng-deep?
- Angular 2模板中的标签是什么意思?