I want to make background image responsive both in width as well as in height so that i can run it in mobile.
I have used this
.your_background_class_name {
width: 100%;
height:auto;
top: 0px;
left: 0px;
z-index: -1;
position: absolute;
}
but it works in width only not in height. What changes should i do to make it work?
Here's how to create responsive background images with CSS: Use the background-size property to encompass the viewport. Give this property a cover value that will tell a browser to scale the background image's heights and width so that they always remain equal to or greater than the height/width of the device viewport.
To make an image responsive, you need to give a new value to its width property. Then the height of the image will adjust itself automatically. The important thing to know is that you should always use relative units for the width property like percentage, rather than absolute ones like pixels.
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.
The best way to stretch an image to fit the background of an element is to use the CSS3 property, for background-size, and set it equal to cover. Take a look at this example of it in action. Here's the HTML in the image below.
html {
background: url(https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSvctt0I--skoKQVfuVt-i4Et6vQ5ve7lXPkLy9sTElCWLKh1Ps) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Know more about background-size
here.
See demo
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