In this article, we’ll see how to use CSS properties such as background-size and background-position to center a background image within a div.
CSS Properties:
Background-Size: The ‘background-size’ CSS property enables scaling of background images to fit available space by adjusting their dimensions.
Background-Position: The CSS background-position property is used to specify where the background image should be placed. This property is used to position the background.
Syntax:
background: url() no-repeat center;
Example 1: In the following example, we use first use the background URL to get the image from the web then we set no-repeat and center after that we set the width to 100% and height of 200px last use the background-size to 350px.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>How to Center a Background Image Inside a Div Using CSS</title>
<style>
.container {
background:
url("https://cdn.pixabay.com/photo/2018/08/14/13/23/ocean-3605547_1280.jpg")
no-repeat center;
width: 100%;
height: 200px;
background-size: 350px;
}
</style>
</head>
<body>
<div class="container"> </div>
</body>
</html>
Example 2: The “container” div has a centered background image, set with “background-position” and “url()” with “no-repeat”. Use “background-size: cover” to fill the div and “background-position: center” to center it. Set “width: 100%” and “height: 500px” for full coverage. To center the “h1” element, use “display: flex; justify-content: center; align-items: center;”.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Center a Background Image Inside a Div Using CSS - Example 2</title>
<style>
.container {
background:
url("https://cdn.pixabay.com/photo/2018/08/14/13/23/ocean-3605547_1280.jpg")
no-repeat;
background-size: cover;
width: 100%;
height: 500px;
display: flex;
justify-content: center;
align-items: center;
background-position: center;
}
h1 {
color: green;
font-size: 3rem;
text-align: center;
text-shadow: 1px 1px 1px crimson;
margin: 0;
padding: 0;
}
@media screen and (max-width: 768px) {
.container {
height: 300px;
}
h1 {
font-size: 2rem;
}
}
</style>
</head>
<body>
<div class="container">
<h1>Welcome To Dev.to!!</h1>
</div>
</body>
</html>
Top comments (0)