A CSS3 and HTML5 Introduction to Responsive Web Design
 
 

How to Code Responsive Web Design

Mobile devices are overtaking desktops in the web browsing world. Instead of browsing the Internet on a desktop or laptop, users are turning towards tablets and smartphones to read websites and buy product. Large companies have dumped millions of dollars into mobile device apps and responsive designs to cater to these user preferences. Responsive designs let you turn your regular desktop web applications into user-friendly mobile websites. Responsive designs use CSS3 and HTML5 to cater to mobile device screen sizes. To dive into the ocean of web design topics, you must know responsive design whether you're designing your own website or someone else's.

What Is Responsive Web Design?

Desktop designs are easy to read on a large monitor. Users can resize fonts and images with the click of a mouse. Bandwidth has increased over the years so megabytes of data don't take too long to download on the Internet. This isn't the case with mobile devices. Small fonts, large files, or large layouts aren't user friendly for mobile devices.

Responsive web design isn't a new concept. When smartphones and data plans were first introduced, web designers attempted to cater to these small screen sizes by using JavaScript. Designers and programmers used JavaScript to detect the user agent passed by a browser, and then resized the layout for smaller screens.

With the release of CSS3, web designers were given the option of media queries. Media queries let you query the size of the screen as the user accesses your site and resize and restructure your layouts according to the screen's dimensions. This eliminated the need for clumsy JavaScript coding, and designers were able to specify a layout based on a screen size without coding specific changes manually.

The rules of responsive design say that you should design for the smallest screen and then continue layout changes as your viewer's screen size increases. This is a change from standard mobile sites. Some web designers prefer to keep their design separate from the main desktop site. These sites are called "m sites," where the "m" is the subdomain name for the mobile site. For instance, if your site is mysite.com, the "m site" would be placed on "m.mysite.com." When the server detects a mobile user, the user is redirected to the mobile site. This design idea is still a viable way to work with mobile devices.

Responsive design is meant to be flexible for site owners. When designers first started detecting smartphones and tablets, there were few screen sizes to work with. Now, there are dozens of devices and screens to work with. Working with JavaScript and several screen sizes can be a nightmare for coders. If the browser doesn't support the JavaScript, the user won't see the changes in the layout. If JavaScript doesn't work with the user's browser and the site owner has a separate mobile site, the user is left to view the desktop site.

Using Media Queries to Adapt to Screen Resolutions

As we mentioned, media queries make it much easier to work with responsive designs. With that in mind, let's jump into some code. Let's take a look at a small media query.

@media screen and (max-width: 300px) {
    div.divclass {
        width: 100px;
    }
}

This media query is somewhat self explanatory if you're used to CSS styles. The first line of code tells the browser that the function is a media query. The query determines the screen size. In this example, the query determines if the user's screen width is no larger than 300 pixels. If the user's screen cannot handle layouts larger than 300 pixels, then the classes are triggered and override any existing styles. Our media query specifies the size of the div container we've used in previous chapters. The CSS style changes the width of the div container to 100 pixels automatically.

Let's plug in our new media query into our HTML page.

<!DOCTYPE html>
<html>
<head>
<title>Your web page title</title>

<style>

body {
    background-color: #000000;
}

div.divclass {
    background: yellow;

    width: 400px;

    height: 100px;
}
img.imgclass {
    border-style: solid;
    border-width: medium;

    position: fixed;
    top: 30px;
}

@media screen and (max-width: 300px) {
    div.divclass {
        width: 100px;
    }
}

</style>
</head>

<body>
<div class="divclass">

</div>

<a href="myotherpage.html" target="_blank">See my other page.</a>

<img class="imgclass" src="myimage.png" alt="My product image">

</body>
</html>

We changed the main desktop "divclass" to create a div container that is 400 pixels in width. Notice that our media query has the same name as the main desktop class. This is because we need to override the main class when a smaller screen is detected.

We also placed the media query at the bottom of our inline styles. Media queries are meant to override current desktop styles. The browser reads styles linearly, so the first desktop "divclass" style loads, and then the media query overrides the style. This is an important concept to understand, or you'll be frustrated when your media queries don't work on smaller screens.

Media queries aren't only for smartphones and tablets. Media queries aren't limited to screens. Media queries also let you use printers, screens and projections. Replace the "screen" property with "print," and your CSS file works with printers and layouts for printing pages through a browser.

Just like CSS, you probably want to place your media query content into a separate file. When you have a change in a media query class, you just need to change the class in one file instead of several. We already discussed the way external stylesheets are linked within HTML files, but media query stylesheets work a bit differently than regular CSS files.

Let's take a look at our same HTML file, but we'll remove the inline media query style and assume we've placed it in a file named "mediastyles.css."

<!DOCTYPE html>
<html>
<head>
<title>Your web page title</title>

<style>

Interested in learning more? Why not take an online Learn HTML - Create Webpages Using HTML5 course?

body {
    background-color: #000000;
}

div.divclass {
    background: yellow;

    width: 400px;

    height: 100px;
}
img.imgclass {
    border-style: solid;
    border-width: medium;

    position: fixed;
    top: 30px;
}

</style>

<link rel="stylesheet" href="mediastyles.css" media="only screen and (max-device-width: 480px)" >
</head>

<body>
<div class="divclass">

</div>

<a href="myotherpage.html" target="_blank">See my other page.</a>

<img class="imgclass" src="myimage.png" alt="My product image">

</body>
</html>

The <link> tag in the above example is similar to linking to a regular CSS stylesheet. The "rel" and "href" attributes are the same as what we've seen before. However, now we have a "media" attribute. This attribute gives direction to the browser, and it specifies when to use the queries. The "only screen" section tells the browser to only use these styles when the device has a screen. In other words, if a reply from the device is a screen resolution, the queries are applied.

The next section of the "media" attribute is the device's max screen size specifications. The "max-device-width" property queries the device for its screen size and determines the maximum width. If the maximum width is 300 pixels (such as a smartphone), the media queries are loaded and applied to the page.

When you work with media queries and responsive designs, you'll need to create a layout for several screen sizes. Start with the smallest screen size and work your way up from there. In other words, you want to design a layout for the smallest screen, and then work with the next screen with a higher resolution. Keep each screen size layout in a separate file to organize your layouts. Then, when you're finished with your responsive design, make sure you test results in several browsers.

Drawing with the Canvas Tag

In older versions of HTML, web designers were forced to use Flash or other third-party tools to draw animations, shapes, lines, and any other 2D objects. With the new HTML5 canvas tag, web designers are no longer forced to use these tools. Instead, you can use draw any 2D shape and animation using JavaScript and HTML5. The canvas tag is becoming a permanent replacement for third-party tools but remember that older browsers don't support HTML5. Therefore, any viewer with an older browser won't be able to view your canvas drawings.

Getting Started with the Canvas Tag

Let's get started with just the basic canvas code that adds a drawing element to your pages. The following code is the format and syntax for the canvas tag.

<canvas id="mainCanvas" width="300" height="300"> </canvas>

The HTML is pretty straightforward. You tell the browser to load a canvas with a width of 300 pixels and a height of 300 pixels. We've named the canvas "mainCanvas" to set it apart from other elements on the page. You'll need this ID to call functions and draw items on the canvas in JavaScript.

Let's add the canvas tag to our HTML page from the previous chapter. The following code is the full page content including the canvas addition.

<!DOCTYPE html>
<html>
<head>
<title>Your web page title</title>

<style>

body {
    background-color: #000000;
}

div.divclass {
    background: yellow;

    width: 400px;

    height: 100px;
}
img.imgclass {
    border-style: solid;
    border-width: medium;

    position: fixed;
    top: 30px;
}

@media screen and (max-width: 300px) {
    div.divclass {
        width: 100px;
    }
}

</style>
</head>

<body>
<div class="divclass"Div content. </div>

<canvas id="mainCanvas" width="300" height="300"> Unsupported browser detected. </canvas>

<a href="myotherpage.html" target="_blank">See my other page.</a>

<img class="imgclass" src="myimage.png" alt="My product image">

</body>
</html>

Just like the video and audio tags, you can also provide default text within the opening and closing canvas tags. The browser will ignore this text and render the canvas normally if it supports HTML5. If the browser doesn't support HTML5, the text "unsupported browser detected" displays instead.

Drawing 2D Figures on Your Canvas

Now that you know how to create a canvas on your pages, it's time to learn how to draw on the canvas. The canvas tag comes with several functions and properties you can use to draw lines, circles, squares and any other shape. You can also draw text on the canvas.

Let's start with drawing a basic shape. Let's draw a straight line. We'll just show you the JavaScript code to make it easier to read, but remember that your JavaScript functions and code must be placed in either an external .js file or inline within a <script> tag.

The following is an example of a straight line in JavaScript.

var c = document.getElementById("mainCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(100,100);
ctx.stroke();

Let's look at the above code line-by-line to understand the drawing function. The first line of code finds the canvas "mainCanvas" on the page and assigns the object to the "c" variable. If the "mainCanvas" tag isn't found, the rest of the code will fail. You must make sure that you give the right ID value to the "getElementById" JavaScript function.

After the JavaScript assigns the canvas tag to the variable, it then identifies the context for the canvas. The "getContext" tag tests the functionality of the canvas tag. This is also a good way to identify if the canvas is available and supported by the browser. You could wrap your canvas drawing functionality inside an "if" statement to include error checking, but we'll exclude error checking for the sake of simplicity and learning.

After the canvas context is identified, it's time to start drawing our shape. In this example, we're drawing a straight line. The first "moveTo" function tells the canvas to move the starting point to the 0,0 location. We mentioned before that the screen can be seen as an x,y axis. The x part of the axis is the horizontal line on the axis that starts at the left side of the screen and moves to the right as the x value increases. The y value starts at the top of the screen and moves down (vertically) the screen as the value increases. The value 0,0 defines the top left corner of the canvas, similar to the screen axis.

Next, we have the "lineTo" function. The "lineTo" function tells the canvas to draw a line to a specific location from the the "moveTo" location. We told the canvas pointer to move to the top left corner of the screen, and then the "moveTo" function tells the canvas to draw a line from the 0,0 location to the 100,100 location. The 100,100 location is 100 pixels from the left of the screen and 100 pixels from the top of the screen. If you give this code a try, you'll see that the result is a diagonal line.

The final line of code tells the canvas to draw the shape. The "stroke" function performs the drawing defined by the previous functions. If you don't call the "stroke" function, nothing will happen on your canvas.

Let's perform another drawing. This time, we'll draw a circle. Using the same concepts as the previous JavaScript functions, the code below draws a circle.

var c = document.getElementById("mainCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(
95,50,40,0,2*Math.PI);
ctx.stroke();

Notice that there are some different functions called with this JavaScript code snippet. The "arc" function takes start, end, and curve values for a circle. You'll need to do a little math when working with circles. You can do a quick lookup for the circle values, or you can perform some tests within the browser to see the different shapes created using the arc function.

You can also add some text to the canvas tag. Use text to add instructions or information for your users. The following JavaScript code shows you how to add text to your canvas.

var c = document.getElementById("mainCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Times New Roman";
ctx.fillText("This is my canvas.",10,50);

The above function is a bit different than what we used with drawing shapes. We only have two functions with text. The first "font" property tells the canvas what font to use. The "30px" value defines the size of the text.

The next function is "fillText." This function takes three parameters. The first parameter is the text you want to display. With this example, the text "This is my canvas" is drawn on the canvas. The next two values are the x,y axis points. The first value is the x coordinate and the second value is the y coordinate. This tells the canvas where to start the drawing. In this example, the canvas starts drawing the text at the 10 pixel point on the x axis and the 50 pixel location on the y axis. In other words, the canvas starts the drawing at the 10,50 coordinates on the canvas map.

Getting Fancier with the Gradients and Animation

Gradients are boxes, circles or other shapes that have a fill color that starts with one value and ends with another. For instance, you might want to fill a square with a gradient that starts with red and ends with white. You can fill your shapes with gradient colors using the canvas tag and JavaScript.

Let's take a look at some basic JavaScript code that paints a square with a fill color from red to white.

var  c=document.getElementById("mainCanvas");
var  ctx=c.getContext("2d");
var  grd=ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
ctx.fillStyle=grd;
ctx.fillRect(
10,10,150,80);

You'll recognize the first two lines of code from previous examples. The next lines of code define the gradient. The "createLinearGradient" tells the canvas that you want to create a linear gradient from one point to the next. You can also create a radial gradient. The values within the gradient function are the start and stop x,y coordinates.

The "addColorStop" function defines the colors you want to use. In this example, we only used two, but you can use numerous gradient colors to fill shapes.

Finally, the "fillRect" draws the rectangle on the canvas. This too takes x,y coordinates to draw the shape.

The final advantage of the canvas tag is its ability to offer animation. Animation is a more advanced feature, and it takes some practice and understanding of the physics of motion and placement of objects.  We'll give you an example of a simple animation. The following code is an example of a circle that spins around the canvas.

var time = new Date();

 ctx.rotate( ((2*Math.PI)/60)*time.getSeconds() + ((2*Math.PI)/60000)*time.getMilliseconds() );

 ctx.translate(105,0);

 ctx.fillRect(0,-12,50,24);

This is a very basic example of animation, but notice the time intervals, the translate function, and the fillRect function. All of these functions play a role in controlling the image and moving it across the canvas.

The canvas tag is one of the more advanced features of HTML5, but with a little practice and effort, you can create rich animations, shapes and text.