CSS - Set Div Width 100% and Resize Keeping Aspect Ratio

后端 未结 4 988
天命终不由人
天命终不由人 2021-01-24 05:03

I have a div with a background image that will overlay part of the header slideshow. I want the width of the div to always be 100% of the window size, even when the user re-size

4条回答
  •  离开以前
    2021-01-24 05:48

    I found a solution which is simple and works great for me. Create a transparent PNG for the aspect ratio you desire, e.g. 15px x 4px.

    put the image within the div. Set the image's width to 100%. It will expand to the div's width and grow in the proper aspect ratio vertically, pushing the div's height down to the proper aspect ratio.

    Something like this (this exact sample untested):

    You could, of course, do this with the other dimension (height) as well by defining it instead of width.

    Simple enough. Works for me.

    -- Andrew

提交回复
热议问题