100% width background image with an 'auto' height

后端 未结 8 1190
慢半拍i
慢半拍i 2020-12-04 08:20

I\'m currently working on a mobile landing page for a company. It\'s a really basic layout but below the header there\'s an image of a product which will always be 100% widt

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 08:53

    Tim S. was much closer to a "correct" answer then the currently accepted one. If you want to have a 100% width, variable height background image done with CSS, instead of using cover (which will allow the image to extend out from the sides) or contain (which does not allow the image to extend out at all), just set the CSS like so:

    body {
        background-image: url(img.jpg);
        background-position: center top;
        background-size: 100% auto;
    }
    

    This will set your background image to 100% width and allow the height to overflow. Now you can use media queries to swap out that image instead of relying on JavaScript.

    EDIT: I just realized (3 months later) that you probably don't want the image to overflow; you seem to want the container element to resize based on it's background-image (to preserve it's aspect ratio), which is not possible with CSS as far as I know.

    Hopefully soon you'll be able to use the new srcset attribute on the img element. If you want to use img elements now, the currently accepted answer is probably best.

    However, you can create a responsive background-image element with a constant aspect ratio using purely CSS. To do this, you set the height to 0 and set the padding-bottom to a percentage of the element's own width, like so:

    .foo {
        height: 0;
        padding: 0; /* remove any pre-existing padding, just in case */
        padding-bottom: 75%; /* for a 4:3 aspect ratio */
        background-image: url(foo.png);
        background-position: center center;
        background-size: 100%;
        background-repeat: no-repeat;
    }
    

    In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value. This works because padding percentage is always calculated based on width, even if it's vertical padding.

提交回复
热议问题