Stretch an image to fill width of browser window

前端 未结 5 1953
谎友^
谎友^ 2021-02-08 12:11

I have an image, and I want the width to fill up the browser window, no matter the size of the window.

How do I do this in HTML and CSS?

相关标签:
5条回答
  • 2021-02-08 12:16

    You can add a div with width an height of 100%, also set image's width and height are 100%

    <div id="wrapper">
        <img src="http://lorempixel.com/200/200" />
    </div>​​​​​​​​​​
    

    CSS:

    #wrapper, img{
        width:100%;
        height: 100%;
    }
    

    jsfiddle

    0 讨论(0)
  • 2021-02-08 12:16
    <div class="fixpixel">
        <img src="ImagePath" />
    </div>​​​​​​​​​​
    

    CSS file

    .fixpixel img{
    height: auto;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
     }
    
    0 讨论(0)
  • 2021-02-08 12:18

    You add the following <meta> element in the head of your HTML document:

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    

    Then you add

    max-width:100%;
    height:auto;
    

    as a CSS rule for both the image and the container of the image. (It can also work for the image without having a container.)

    And you add

    body {
        margin: 0;
    }
    

    to get rid of the margin around the image and/or container. This is how your image will fill the whole width of the screen, no matter what size the screen is.

    0 讨论(0)
  • 2021-02-08 12:31
    <img src="filename.jpg" alt="alt text" width="100%" />
    

    This assumes that the image's container is as wide as the browser window.

    0 讨论(0)
  • 2021-02-08 12:35

    The margin of the body element is set to a default of 8px, which is the space you are seeing which prevent the image to stretch the full width and height of the screen.

    You can include

    body {margin: 0px;}
    

    to prevent this behavior, which I guess was put in place to prevent unstyled pages to present the content pushing to the edge of the page. It was discussed here.

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