Making an image width:100% inside a inline-block element

后端 未结 3 1712
孤街浪徒
孤街浪徒 2021-01-22 04:56

If I have an image on a page with width set to 100% in css it is as wide as the browser. Fine. However, if I make a containing div have display:inline-block, then the image is n

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-22 05:43

    This is because a percentage value on width is relative to the width of the box's containing block. While a block-level container (

    element, for instance) takes the entire width of its containing block, an inline-level element doesn't.

    Therefore you have to specify the width of the wrapper

    explicitly. As a thumb rule, when you say 100% you should ask yourself 100% of what?

    img { width:100%; }
    div { display:inline-block; width: 100%; }
    
    


    Alternatively, in cases where you want to set the width of elements as the width of the viewport/window, you could use viewport percentage units instead. For instance:

    img { width: 100vw; } /* 1vw = 1/100 of the width of the viewport */
    

    Demo:

    img { width: 100vw; }
    
    

提交回复
热议问题