Resize an image using CSS

I have a question about resizing an image in CSS.

I have a 1920x1080 image.

This image should be automatically resized to fit any screen, however I cannot do this.

Example of what i want here

A video starts playing upstairs since I want you to be my page, but instead of the video, in the picture.

My HTML:

<body> <div id="slides"> <ul> <li><img src="_img/img1.jpg"></li> <li><img src="_img/img2.jpg"></li> <li><img src="_img/img3.jpg"></li> <li><img src="_img/img4.jpg"></li> </ul> </div> 

All images inside a div called slides should fit on any screen.

+5
source share
4 answers

First of all, you have to insert meta viewport into your head , like this

 <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> 

then here is a snippet of how you could do this work.

 body { margin: 0; padding: 0 } ul, li { list-style: none; margin: 0; padding: 0 } #slides img { max-width: 100%; display: block /*fix inline image small gap*/ } /*larger devices than the size of image */ @media (min-width: 1920px) { #slides img { width: 100% } } 
 <div id="slides"> <ul> <li> <img src="http://lorempixel.com/1920/1080"> </li> <li> <img src="http://lorempixel.com/1920/1080"> </li> <li> <img src="http://lorempixel.com/1920/1080"> </li> <li> <img src="http://lorempixel.com/1920/1080"> </li> </ul> </div> 
+2
source

Try setting <img> to the width property of 100%, which limits the width of the image to the width of the window.

 <li><img src="_img/img1.jpg" width="100%"></li> 

Demo Screenshot

CSS

 li > img { width:100%; } 

For optimization for mobile users, you can also set the viewport as the width of the device , for example:

 <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> 
+2
source

You should add to your CSS:

 #slides img { width: 100%; height: auto; } 

This allows images to fit the width of the container and maintain aspect ratio.

+2
source

I suggest you use the background for li instead of img as follows:

 <body> <div id="slides"> <ul> <li id="img1"></li> <li id="img2"></li> <li id="img3"></li> <li id="img4"></li> </ul> </div> 

then you just set the global background property (CSS):

 #slides li { width: 100%; height: 100%; background-size: cover; background-repeat: no-repeat; } 

and set single background images individually (CSS)

 #img1 { background: url(the_url_1.jpg); } #img2 { background: url(the_url_2.jpg); } 

the background-size property does the magic:

  • if you set it as cover , you scale the background image as much as possible so that the background area is completely covered by the background image. Some parts of the background image may not be displayed in the background positioning area;

  • if you set it as contain , you scale the image to the largest size so that its width and height can fit into the content area;

+2
source

All Articles