SciFi
SciFi

Reputation: 119

CSS property "background-image" work for body and not for class

As in the title, the problem is that background-image works only if I use it with body, but it doesn't work if I use it for example to the .main class. Why?

An example of what doesn't work:

.main{
  background-color: #ffffff;
  background-image: url(https://i.sstatic.net/DwaJj.png);
  background-size: cover;
  background-repeat: no-repeat;
  margin-left: 160px; /* Same as the width of the sidenav */
  font-size: 28px; /* Increased text to enable scrolling */
  padding: 0px 10px;
}
<body>
  <div class="main">

  </div>
</body>

This working properly.

body{
    background-color: #ffffff;
    background-image: url(https://i.sstatic.net/DwaJj.png);
    background-size: cover;
    background-repeat: no-repeat;
}
.main{
    margin-left: 160px; /* Same as the width of the sidenav */
    font-size: 28px; /* Increased text to enable scrolling */
    padding: 0px 10px;

}
<body>
  <div class="main">

  </div>
</body>

Upvotes: 1

Views: 755

Answers (3)

Subrato Pattanaik
Subrato Pattanaik

Reputation: 6049

The default value of the height property is auto for all elements. Since there is no element present in the div element so the height of the div element is 0 in your case, so the image is not fit in the div element.

You can set the height of the div element to auto or any pixel value(if the value exceeds it will overflow ).

height: auto; or height: 20px:

@Edited:

According to the official docs, The background of the root element becomes the canvas background and its background painting area extends to cover the entire canvas.

The HTML element is the root element. Now, according to your case, you have set the background image to body element and not in HTML element. Thanks to background propagation it will check the background for the root element first and if it is not there then it will propagate to body element background. As you have set the background image to body so the background image will apply to whole canvas.

Tip: Canvas size is infinite but user agent set its size to the target device.

Upvotes: 4

Friday Ameh
Friday Ameh

Reputation: 1684

By default, your Html and body elements are only as high as the actual page content and the div element has a height of 0 so even if the background is applied the height is 0 and cannot show. Simple add height to your main CSS like so.

    .main{
        margin-left: 160px; /* Same as the width of the sidenav */
        font-size: 28px; /* Increased text to enable scrolling */
        padding: 0px 10px;
        height: 400px;
    }

Upvotes: 3

Trần Hữu Hiền
Trần Hữu Hiền

Reputation: 1044

I think it will work for class. But your div has not anything. Just try add:

width: 500px;
height: 500px; 

into your class.

Upvotes: 3

Related Questions