Stretch and scale a CSS image in the background - with CSS only

后端 未结 22 2193
迷失自我
迷失自我 2020-11-22 01:37

I want that my background image stretch and scale depending on the browser viewport size.

I\'ve seen some questions on Stack Overflow that do the job, like

相关标签:
22条回答
  • 2020-11-22 01:41
    background-size: 100% 100%; 
    

    stretches the background to fill the entire element on both axes.

    0 讨论(0)
  • 2020-11-22 01:42

    CSS3 has a nice little attribute called background-size:cover.

    This scales the image so that the background area is completely covered by the background image while maintaining the aspect ratio. The entire area will be covered. However, part of the image may not be visible if the width/height of the resized image is too great.

    0 讨论(0)
  • 2020-11-22 01:42

    If you want to have the content centered horizontally, use a combination like this:

    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    

    This will look beautiful.

    0 讨论(0)
  • 2020-11-22 01:44

    Do you want to achieve this just using one image? Because you can actually make somewhat similar to a stretching background using two images. PNG images for instance.

    I've done this before, and it's not that hard. Besides, I think stretching would just harm the quality of the background. And if you add a huge image it would slow down slow computers and browsers.

    0 讨论(0)
  • 2020-11-22 01:45

    You can use the border-image : yourimage property to scale the image up to the border. Even if you give the background-image, the border image will be drawn over it.

    The border-image property is very useful if your style sheet is implemented somewhere which doesn't support CSS 3. If you are using Google Chrome or Firefox, then I recommend the background-size:cover property itself.

    0 讨论(0)
  • 2020-11-22 01:47

    I wanted to center and scale a background image, without stretching it to the entire page, and I wanted the aspect ratio to be maintained. This worked for me, thanks to the variations suggested in other answers:

    INLINE IMAGE: ------------------------

    <div id="background">
        <img src="img.jpg" class="stretch" alt="" />
    </div>
    

    CSS ----------------------------------

    html {
        height:100%;
    }
    
    #background {
        text-align: center;
        width: 100%; 
        height: 100%; 
        position: fixed;
        left: 0px; 
        top: 0px; 
        z-index: -1;
    }
    
    .stretch {
        margin: auto;
        height:100%;
    }
    
    0 讨论(0)
提交回复
热议问题