Why doesn't the background image show up without specific width and height?

后端 未结 5 1769
不思量自难忘°
不思量自难忘° 2020-12-16 16:15

Here\'s an example code

I\'ve been wondering why the background-image doesn\'t show up unless I specific the image\'s width and height in pixels. I trie

相关标签:
5条回答
  • 2020-12-16 16:45

    If you don't specify height, the size of your div is given by the size of its contents, i.e. it's 0x0, so you don't have much chance of seeing a background image. Add

    border: 1px solid red;
    

    to see how large your div is (or isn't).

    0 讨论(0)
  • 2020-12-16 16:52

    Your <div> element don't have any content, so the <div> height is 0px.
    The width of the <div> is still 100%.
    If you add any content to the div it will have some height and it will show a portion of image.
    <body> by default has the height of the window, so you can see the background-image.

    0 讨论(0)
  • 2020-12-16 16:53

    I found a great alternative without specifying the height, thanks to http://blog.brianjohnsondesign.com/maintain-aspect-ratio-for-html-element-using-only-css-in-a-responsive-design/. HTML

    <div class="pic"></div>
    

    CSS

    .pic {
      background: url("http://i.imgur.com/HIt6f8r.png") no-repeat;
      display: block;
      position: relative;
      width: 20%;
      height: 0;
    padding-bottom: 20%;
      background-size: 100%;
    }
    

    All you need to do, assuming that it's a square, to match the padding-bottom to the width in css.

    Update: I also heard about another solution that may be useful. http://www.mademyday.de/css-height-equals-width-with-pure-css.html

    CSS

    .pic {
    position: relative;
    width: 50%; 
    }
    .pic:before {
    content: "";
        display: block;
        padding-top: 100%;  
    }
    

    although I haven't tested it out yet....

    0 讨论(0)
  • 2020-12-16 17:09
    <div class="pic"></div>
    

    Div is container, it expects to have inner elements, when it's empty you must explicitly define height.

    0 讨论(0)
  • 2020-12-16 17:09

    Your background image will not show because the div element has no content, this means that its height is 0.

    You could use this jQuery code to make your div take the size of the window.

    $(function () {

    'use strict';
    $('.div').height($(window).height());
    
    $(window).resize(function () {
        $('.div').height($(window).height());
    
    })
    

    });

    0 讨论(0)
提交回复
热议问题