CSS Div Background Image Fixed Height 100% Width

后端 未结 3 1518
孤独总比滥情好
孤独总比滥情好 2021-02-02 07:20

I\'m trying to setup a series of div\'s with a background image that each have their own fixed height, and stretch to fill up the width, even if there is overflow on the top/bot

相关标签:
3条回答
  • 2021-02-02 07:50

    See my answer to a similar question here.

    It sounds like you want a background-image to keep it's own aspect ratio while expanding to 100% width and getting cropped off on the top and bottom. If that's the case, do something like this:

    .chapter {
        position: relative;
        height: 1200px;
        z-index: 1;
    }
    
    #chapter1 {
        background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
        background-repeat: no-repeat;
        background-size: 100% auto;
        background-position: center top;
        background-attachment: fixed;
    }
    

    jsfiddle: http://jsfiddle.net/ndKWN/3/

    The problem with this approach is that you have the container elements at a fixed height, so there can be space below if the screen is small enough.

    If you want the height to keep the image's aspect ratio, you'll have to do something like what I wrote in an edit to the answer I linked to above. Set the container's height to 0 and set the padding-bottom to the percentage of the width:

    .chapter {
        position: relative;
        height: 0;
        padding-bottom: 75%;
        z-index: 1;
    }
    
    #chapter1 {
        background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
        background-repeat: no-repeat;
        background-size: 100% auto;
        background-position: center top;
        background-attachment: fixed;
    }
    

    jsfiddle: http://jsfiddle.net/ndKWN/4/

    You could also put the padding-bottom percentage into each #chapter style if each image has a different aspect ratio. 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.

    0 讨论(0)
  • 2021-02-02 07:51

    http://jsfiddle.net/ndKWN/1/

    You can use background-size: cover;

    0 讨论(0)
  • 2021-02-02 08:03

    But the thing is that the .chapter class is not dynamic you're declaring a height:1200px

    so it's better to use background:cover and set with media queries specific height's for popular resolutions.

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