Reputation: 4662
I have to load an (header) image at the top of the site depending on a variable passed in to the site. I can do this but I can only do this if it is a background image, as far as I know.
This is what I am doing in the css for the load of the image:
#headerimg
{
background-image: url('/Content/CompanyFiles/spi/image3.jpg');
background-repeat: no-repeat;
background-position: center center;
width: 600px;
height: 133px;
margin: 0;
padding: 0px;
}
and my html code:
@using MvcBootstrap.MiscClasses
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
<link href="@Url.Content(string.Format("~/Content/CompanyFiles/{0}/{0}.css?t={1}", MySession.CssName, DateTime.Now.Millisecond))" rel="stylesheet" type="text/css" />
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="img-responsive" id="headerimg"></div>
<div class="content">
<div class="jumbotron">
<h2>Payment Portal</h2>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</div>
</body>
</html>
If I change the css to 100% size, that div isn't shown since there is no content and the image is just a background image, so it collapses.
If I set the div to a specific size, then it stays that size and it will not resize on the page resize.
I need to be able to dynamically insert an image in there based on the css page loaded but resize if used on a smaller device.
Is this possible? Thank you!
Upvotes: 2
Views: 15875
Reputation: 21675
Here is how you use a responsive background image, divide height
by width
and multiply by 100
. That will be your bottom padding. Then use cover
for background-size:
so it will stretch with the element.
header {
height: 80px;
background-color: gold;
}
.hero {
padding-bottom: 37.5%; /* = ( 600 / 1600 ) x 100 */
background-image: url( 'http://placehold.it/1600x600/A00' );
background-size: cover;
}
<header></header>
<div class="hero"></div>
Upvotes: 6