I have a an image taking up the entire height of the viewport. The image height should span the entire viewport height (100%) so that it will fit to the screen it is viewed from (already accomplished here) and the width should be relatively proportional to the height. As you can see in my page (http://lamininbeauty.co.za), the page has space on the sides. I want the image to center horizontally. Below is my code:
CSS:
body{
margin: 0px;
padding: 0px;
overflow: hidden;
}
#main{
margin: auto;
}
img.bg {
/* Set rules to fill background */
max-height: 100%;
/* Set up proportionate scaling */
height: auto;
/* Set up positioning */
position: fixed;
}
HTML:
<body>
<div id="main">
<img class="bg" src="images/massage2.jpg" border="none" />
</div>
</body>
Note: I do not want the image to lose aspect ratio and it should always fit in vertically 100%, none of the image being cut off and no vertical scrolling. Horizntal centering. I try to stay away from the background-size property since IE8 and lower does not support it.
Using CSS, you can set the background-size property for the image to fit the screen (viewport). The background-size property has a value of cover . It instructs browsers to automatically scale the width and height of a responsive background image to be the same or bigger than the viewport.
Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.
To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
Simply add left:0;right:0;margin:0 auto;
to img.bg
(example):
body{
margin: 0px;
padding: 0px;
overflow: hidden;
}
#main{
margin: auto;
}
img.bg {
/* Set rules to fill background */
max-height: 100%;
/* Set up proportionate scaling */
height: auto;
/* Set up positioning */
position: fixed;
/* Align horizontally */
left:0;
right:0;
margin:0 auto;
}
If you want the image to never be cut off (horizontally or vertically), and always centered, try this code instead (from https://stackoverflow.com/a/6284195/526741):
<img class="absoluteCenter" src="PATHTOIMAGE">
/* Don't Change - Positioning */
.absoluteCenter {
margin:auto;
position:fixed;
top:0;
bottom:0;
left:0;
right:0;
}
/* Sizing */
img.absoluteCenter {
max-height:100%;
max-width:100%;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With