Html 如何使 div 容器响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38017547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How make a div container responsive?
提问by JuanPer
I have a div with a background-image assigned in the CSS3 file. The image is responsive, so it scales according to the screen size BUT the container keeps the height at all screen sizes.
我有一个 div,在 CSS3 文件中分配了一个背景图像。图像具有响应性,因此它根据屏幕尺寸进行缩放,但容器在所有屏幕尺寸下都保持高度。
I need to know if there is a way to make the container responsive as well as the background image.
我需要知道是否有办法使容器响应以及背景图像。
HTML:
HTML:
<div class="responsive> </div>
CSS3:
CSS3:
.responsive {
background: url('https://s20.postimg.org/o09gf7fvx/bag.jpg') no-repeat center top;
border: 1px solid red;
background-size: contain;
width: 100%;
height: 270px;
}
I must use background-image selector and no img src tag. Here is the fiddle file.
我必须使用背景图像选择器并且没有 img src 标签。这是小提琴文件。
Thank you.
谢谢你。
回答by Chris Hilditch
This can be done an additional dummy element, inside the element you want to keep at a fixed ratio. If you specify a padding-top or padding-bottom as a percentage, that is in terms of the width of the container element, and this then keeps the height of the container element at a fixed ratio.
这可以通过一个额外的虚拟元素来完成,在你想要保持固定比例的元素内部。如果您将 padding-top 或 padding-bottom 指定为百分比,即根据容器元素的宽度,然后将容器元素的高度保持在固定比例。
<div id="responsive">
some text
<div id="dummy"></div>
</div>
CSS:
CSS:
#responsive {
display: inline-block;
position: relative;
width: 100%;
background: url('https://s20.postimg.org/o09gf7fvx/bag.jpg') no-repeat center top;
background-size: contain;
}
#dummy {
padding-top: 29%;
}
Working Example:
工作示例:
https://jsfiddle.net/098jj61q/
https://jsfiddle.net/098jj61q/
Credits:
学分:
回答by Saurabh Sonawane
Yes its correct. According to @Paulie_D, you can't do that with background image.As per your requirement you can do that using imgtag only.
是的,它是正确的。根据@Paulie_D 的说法,您不能使用背景图片来做到这一点。根据您的要求,您只能使用img标签来做到这一点。
What you have to do, without using the div just make the image responsive by treating it as a block element as,
你必须做的,不使用 div 只是通过将其视为块元素来使图像具有响应性,
.img-responsive {
display: block;
max-width: 100%;
height: auto;
}
or if you insist to use division with background image then cover the backgound image and set min-height as,
或者,如果您坚持对背景图像使用除法,则覆盖背景图像并将最小高度设置为,
div.mydiv {
background:url(background_image.jpg);
background-repeat:no-repeat !important;
background-size: cover !important;
background-position:center center !important;
min-height:300px;
}