Home »
CSS
How to set perfect image background with CSS?
In this article, we will learn how to create and set a perfect image background with CSS inside an element?
Submitted by Abhishek Pathak, on October 22, 2017
While CSS is quite advanced, but new designers often find themselves stuck when things doesn't go their way in CSS. Setting background image and positioning is one of those nasty problems that new designers avoid using in their web pages, unfortunately missing the CSS capabilities that can produce wonderful effects.
CSS has really cool background properties. Setting color and gradients in CSS are piece of Cake. If you haven't read the (how to create gradients with CSS3?), do check it out. With background-image and background-size, we can give any element a perfect image background, that doesn't look stretched to fit in the element.
Let's understand this practically,
HTML with CSS
<!DOCTYPE html>
<html>
<head>
<title>CSS perfect image demo</title>
<style>
.box {
width: 300px;
height: 300px;
background-image: url('http://jgospel.net/media/93206/.108503.bt.jpg');
background-size: cover;
background-position: center center;
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>
Output
Starting with the HTML, we have a div element with class box which we will use to select the element in CSS.
Coming to CSS, we have selected the .box div element and we assign width and height to the box element, so that it can render in the browser. Next, we set a background image using background-image property and giving it the URL of the image. Next, we add background-size property and set its value to cover, which means the image will cover the background completely without stretching.
But this makes our background image to show from the top left corner. Because most images have main content at the center, we use background-position to position it to the center. The first center is to horizontally center the image and other center is to vertically center the image.
And there you go, perfect background image for an element.
DEMO
CSS Tutorial & Examples »