How to do responsive images in HTML & CSS

This is the need of the hour as more and more people are using mobiles for accessing web pages. How to make sure that the image you inserted in HTML is adapting to the mobile view is very crucial in accessibility point of view. You can do it using simple CSS codes.

You can do it in two way. First one is by shrinking the image in a mobile. The second one is by swapping the image with a smaller image in a mobile. You can see both in the example below.

Here is the desktop view 


Here is the mobile view


Code for both shrinking the image and swapping the image in a mobile


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Automatic resizing of image in mobile view</title>
<STYLE type="text/css">

@media only screen and (max-width: 480px) {

.mobileHide {
display: none !important;
}
.mobileShrink {
width: 100% !important;
max-width: 300px !important;
display: block !important;
}
.mobileSwap {
display: block!important;
width: auto!important;
overflow: visible!important;
float: none !important;
height: inherit!important;
max-height: inherit!important;
}
}

</style>
</head>

<body>
<h2 />Image shrinking </h2>
<img src="img900-300.gif" class="mobileShrink" />

<h2>Image swapping </h2>
<img src="img900-300.gif" class="mobileHide" />
<DIV class="mobileSwap" style="display: none; width: 0px; overflow: hidden;  max-height: 0px;"><img src="img300-100.gif" /></div>


</body>
</html>

Comments

Popular posts from this blog

How to select and cut out an image in Krita

Transform and Stretch an image in Krita

Joomla error: Your site may not have been upgraded completely