Creating responsive HTML containers in CSS

Creating responsive HTML containers in CSS

With the increasing use of smartphones and tablets, the demand and benefits of responsive web designs are an ever increasing importance. A responsive web design means a design that works flexibly on a wide-variety of screen resolutions, from smartphones all the way to desktop computers – all from one codebase, so to speak.

As a web developer, you might be curious to learn how responsive designs can be created. Thankfully, the learning curve isn’t complicated at all. In fact, there are many responsive design frameworks you can use to help you, too. A popular free design framework called Bootstrap, released under an MIT license, is a favourite among many developers and is a great option to consider if you need to design a fully-responsive website from scratch.

For the purposes of this article, we’ll be showing you how to create a grid of containers that are flexible and respond dynamically to the available horizontal space. No JavaScript is needed. View the demo here (right click on the page for the full source code).

HTML:

<div>Container 1</div>

<div>Container 2</div>

<div>Container 3</div>

<img src=”google.png” alt=“Google”>

CSS:

div
{

float: left;
width: 33.333%;
height: 100px;

}

@media screen and (max-width: 800px)
{
div
{

float: none;
width: 100%;

}
}

img
{
width: 100%;
max-width: 800px;
max-height: 290px;
}

As you can see, we have three equally-sized containers that are either floated or stacked depending on the available horizontal space. If the viewport width is 800 pixels or less, the containers become stacked at 100% width; ideal for smartphones where horizontal space becomes a major issue. The “@media screen and (min-width: 800px)” is a media query. It allows specific CSS code to be limited to certain types of devices or resolutions. Media queries are not supported in IE 8 and earlier; to support older browsers, you’ll need to use a JavaScript library such as Respond.js.

Responsiveness isn’t just limited to HTML containers; you can also do the same for images, too. It simply involves specifying the maximum height of an image and setting the width to 100%. Specifying a maximum width prevents potential image stretching on large resolutions.

And that’s all there is to it. Of course this is just a basic example, but it gives you a starting point to creating responsive designs that scale regardless the device it is viewed on.

Ben Stones

Sharing

Leave your comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.