Billjk
Billjk

Reputation: 10686

Stretch an image to fill width of browser window

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?

Upvotes: 20

Views: 77691

Answers (5)

sbagdat
sbagdat

Reputation: 850

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="https://picsum.photos/200/200">
</div>​​​​​​​​​​

CSS:

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

jsfiddle

Upvotes: 18

DianaHeit
DianaHeit

Reputation: 31

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.

Upvotes: 2

SLop
SLop

Reputation: 31

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.

Upvotes: 0

Sabarish R
Sabarish R

Reputation: 81

<div class="fixpixel">
    <img src="ImagePath" />
</div>​​​​​​​​​​

CSS file

.fixpixel img{
height: auto;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
 }

Upvotes: 2

Brian Willis
Brian Willis

Reputation: 23854

<img src="filename.jpg" alt="alt text" width="100%" />

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

Upvotes: 8

Related Questions