Home > Back-end >  background-img doesn't show after linked in css, but showed if I added the img to html
background-img doesn't show after linked in css, but showed if I added the img to html

Time:10-24

So when I try to define the background-image for the below html:

 <div class="generalVideo">
            
            <div id='generalButton'> 
            </div>
        </div>

like so in css:

#generalButton{
    background-image:url(files/gss.png);
    background-position:center center;
    background-repeat: no-repeat;
    background-size: 70%;
}

nothing shows up.

However, if I keep the css the same and add an image to the html like so:

<div class="generalVideo">
            
            <div id='generalButton'> <img src="files/gss.png" alt="">
            </div>
        </div>

So you can see the two images overlapping on each other in different positions. If I deleted the background-image from the css, the img in the html also disappears. Why is this happening?

CodePudding user response:

In the first instance there are no dimensions for the background-image to take up so nothing shows.

In the second instance the img is an element within the HTML and in the absence of any other styling it shows at its 'natural' dimensions.

Also, by default, the parent div will take on width and height: auto so essentially the img gives it some width and height. So the background-image also has some dimensions to work with and can be set up at 70% as required.

To get just a background image to show you need to tell the system a width and height. This snippet gives it a square in terms of vmin units:

#generalButton {
  background-image: url(https://picsum.photos/id/1015/200/300);
  background-position: center center;
  background-repeat: no-repeat;
  background-size: 70%;
  background-color: pink;
  width: 50vmin;
  height: 50vmin;
}
<p> background-image only, no img element: </p>
<div class="generalVideo">

  <div id='generalButton'>
  </div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Note: the div has been given a background color too so it's size is obvious.

CodePudding user response:

They overlap because the background-image is centered and the img-tag is not.

You need to set a width and height on the div if you only want to use the div.

#generalButton {
    background-image:url(https://picsum.photos/200);
    background-position:center center;
    background-repeat: no-repeat;
    background-size: 70%;
    height: 200px;
    width: 200px;
}
<div class="generalVideo">       
  <div id='generalButton'>
    <img src="https://picsum.photos/150" alt="">
  </div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related