问题
I need the following:
- emtpy div with no content
- background image set to the div the
- background image to be fluid/responsive on re-size I cannot set fixed
- dimensions on the div
Everything I try fails to force the div open to support the size of the background image. Any help is greatly appreciated...
http://www.everymountain.us/
<header id="header">
<div class="wrapper">
<div class="inner">
<div class="top_banner"></div>
</div>
<div class="clear"></div>
</div>
</header>
.front #header .top_banner { background: url('images/bg_front.jpg') no-repeat; background-size: cover; }
回答1:
The way to lock a height's aspect ratio to it's fluid width is to use padding-top
or padding-bottom
percentage. This is because all padding percentages are of the the element container's width. Your background image is 960 x 520, so the height is 54.166666666667%.
html
<div class="top_banner"></div>
css
.top_banner {
background-image: url('images/bg_front.jpg');
background-size: 100%;
width: 100%;
padding-top: 54.166666666667%;
height: 0;
}
Example: http://jsfiddle.net/SsTZe/156/
Essentially the same question: CSS fluid image replacement?
回答2:
You can handle it after applying CSS
#DivName{
background-size: auto auto;
}
here first auto is for width and second is for height
回答3:
Try to use medie queries in your CSS for different screen sizes to handle different fixed heights. For example:
@media (min-width: 1200px) {
div { height: 3em; }
}
@media (min-width: 768px) and (max-width: 979px) {
div { height: 2em; }
}
@media (max-width: 767px) {
div { height: 1.2em; }
}
@media (max-width: 480px) {
div { height: 1em; }
}
etc. what you need to customize. You can leave the div width 100% to fit for all screen and the background-size:cover. You can also make different size backgrounds (diff. files) for each screen sizes to give less size to your website for mobile or tablet devices.
回答4:
Since this is a top google result for creating fluid-height divs in general (not just empty ones like the question specifies), I wanted to leave a CSS Calc solution that lets you put content into the div (the padding trick forces it to be empty):
.my-div {
background: #ccc url(https://link-to-image/img.jpg) no-repeat 50% 0;
background-size: 100% auto;
width: calc(100vw - 350px);
height: calc((100vw - 350px) * 0.468795); /* replace the decimal with your height / width aspect ratio */
}
来源:https://stackoverflow.com/questions/16563730/need-empty-div-with-background-image-to-force-height-and-must-be-responsive