0

I am trying to execute some simple container code to center an image, I cannot find it why my Container has a height of 0.

#test {
    background-image: url('https://via.placeholder.com/150');
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;
}


<div class="container">
    <div class="row">
        <div class="col">
            <div id="test">

            </div>
        </div>
    </div>
</div>

Why does the container have a height of 0, and hence my image not appearing?

J.Doe
  • 51
  • 6

3 Answers3

0

By default, block elements get their heights from their content. Content meaning what goes between the opening and closing tag of the element in the HTML. A background image would not be content, but can be thought of more like decoration.

You can set the height manually with css to whatever you like. Keep in mind though that an empty element is unsemantic code.

slacle
  • 503
  • 4
  • 13
0

Adding a height property could fix this as mentioned by you in comments.

Another alternative that would solve the problem with varying image sizes could be to use an img tag inside #test element.

<div id="test" style="background-image: url(/my-image.jpg);">
 <img src="/my-image.jpg" style="visibility: hidden;" />
</div>

This way the div takes up the height based on the image size.

YetAnotherBot
  • 1,937
  • 2
  • 25
  • 32
0
<div class="text-center d-flex" style="height: 100vh">
    <div class="container m-auto">
        <div class="row">
            <div class="col-8 mx-auto">
                <h1> YOU CAN DO IT </h1>
            </div>
            <div class="col-8 mx-auto">
                <h1> I should be centered </h1>
            </div>
        </div>
    </div>
</div>

Using margin:auto to vertically-align a div

As the second answer from the linked stackoverflow question over, it was because my parent was not of type flex.

J.Doe
  • 51
  • 6