How to set an image properly as background?

Viewed 68

I am trying to set an image as a background but the zoom version of image is coming.

My code


<!DOCTYPE html>
<html>
<head>
<style>

body, html {
  height: 100%;
}
.bg {
  /* The image used */
  background-image: url("../../media/image1.jpeg");

  /* Full height */
  height: 100%;

  /* Center and scale the image nicely */
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}
</style>
</head>
<body class="bg">
</body>
</html>

How can I fix it?

1 Answers

You can use the propertie background-size, here is a following guide:

background-size: auto

Default value. The background image is displayed in its original size:

div{
  width:100px;
  height:100px;
  border:5px solid blue;
  background-image:url("https://googlechrome.github.io/samples/picture-element/images/kitten-small.png");
  background-size:auto;
}
<div></div>

background-size: lenght Sets the width and height of the background image. The first value sets the width, the second value sets the height. If only one value is given, the second is set to "auto". Read about length units

div{
  width:100px;
  height:100px;
  border:5px solid blue;
  background-image:url("https://googlechrome.github.io/samples/picture-element/images/kitten-small.png");
  background-size:10px;
}
<div></div>

background-size: percentage

Sets the width and height of the background image in percent of the parent element. The first value sets the width, the second value sets the height. If only one value is given, the second is set to "auto"

div{
  width:100px;
  height:100px;
  border:5px solid blue;
  background-image:url("https://googlechrome.github.io/samples/picture-element/images/kitten-small.png");
  background-size: 10%;
}
<div></div>

background-size: cover >good answer for this question<

Resize the background image to cover the entire container, even if it has to stretch the image or cut a little bit off one of the edges

div{
  width:100px;
  height:100px;
  border:5px solid blue;
  background-image:url("https://googlechrome.github.io/samples/picture-element/images/kitten-small.png");
  background-size:cover;
}
<div></div>

background-size: contain >the best answer for this question<

Resize the background image to make sure the image is fully visible

div{
  width:100px;
  height:100px;
  border:5px solid blue;
  background-image:url("https://googlechrome.github.io/samples/picture-element/images/kitten-small.png");
  background-size:contain;
}
<div></div>

background-size: initial

Sets this property to its default value.

background-size: inherit

Inherits this property from its parent element.

Source on background-size

Suggestion on following up read

Related