Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

HTML5 and CSS3 Part 4: Page Layouts

5.00/5 (4 votes)
6 Apr 2014CPOL21 min read 11.4K  
Diving into how to get items to show up in the right place on our page.

Introduction

In our continuing journey to understand HTML and CSS better, we come to the point where we want to lay things out on the page. Instead of having everything be left-aligned and stacked top to bottom, we want to figure out how to position things all over the page in an intelligent manner. That is the focus of this article. Our starting point is a very basic understanding of HTML and CSS. By the time we are finished, we want to know the best ways to lay items out on a web page.

Important Tags

There are a couple important tags that we need to go over before we dive too deep into layouts. These HTML tags will help us identify and position elements on the page. They also help us define what items go together. Let's look at the two tags and figure out how they are used and what their differences are.

Div

The first tag is one that you will see in practically every web page you look at. The div tag is a block-element used to group sections of HTML together. The term "block-element" means a couple things. First, it means that it puts space above and below it on the rendered page (like a paragraph tag does). Second, it indicates that the items inside are a cohesive unit. For instance, if you were building a house out of HTML, each room might be wrapped in a div. Then, you might wrap all of the first floor rooms with a div and finally, the entire house might be wrapped in a div. This allows us to style each room individually (size, shape, etc.), but we can also apply styles to entire floors of our house (color, etc.) and to the entire house (outside[border] color, etc.)

That brings up a point about div sections: they can be nested. Let's build out our "house" in HTML to see how it would look:

HTML
<div id="house">
   <div id="first-floor">
      <div id="ff-bathroom" class="bathroom">
      </div>
      <div id="ff-diningroom">
      </div>
      <div id="ff-kitchen">
      </div>
      <div id="ff-livingroom">
      </div>
   </div>
   <div id="second-floor">
      <div id="sf-bathroom" class="bathroom">
      </div>
      <div id="sf-bedroom1" class="bedroom">
      </div>
      <div id="sf-bedroom2" class="bedroom">
      </div>
      <div id="sf-bedroom3" class="bedroom">
      </div>
   </div>
</div>

One point to bring up right away, just to be clear here: this does not somehow render a house on screen. This is just an illustration of back-end HTML layouts. This demo is just to identify how layouts work. We will get to how to use them effectively below. OK, now that we have that out of the way, let's look at a couple important things that this demo brought up.

First, a div can have a class or an id, just like any other HTML element. In fact, you will almost certainly be putting one or both attributes on almost all of your divs. The reason why is because you need a way to identify that particular div or that type of div in order to apply styles to it via CSS.

Second, note that I mixed the usage of id and class based upon how I wanted to identify the item. For instance, I identified the first floor bathroom "room" div with the id of "ff-bathroom" but I also put a class on it of "bathroom". This is because I might have a style that applies to bathrooms, regardless of which floor they are on. The same is true for the bedrooms. Just as a reminder, you use id to uniquely identify an element and you use class to apply the same styles to one or more elements.

Span

The second element we want to look at for layout purposes is the span element. This is an in-line element that groups items together. Sounds similar to a div, right? In many ways it is but there are a couple of crucial differences. The first difference is the "in-line" part. The span element is meant to be used in a way that does not disrupt your layout. That means you can use a span element in the middle of a paragraph and you would not know it was there on the rendered page. We will look at how that works and why we would want it in a bit. The second difference is that a span can only have other in-line elements inside it. You cannot put a div inside of a span but you can put a span inside a div.

How does all of this work and why do we want to use span? Let's take a look at an example. Say you are writing a paragraph and you want to highlight a key sentence. To do this, you would wrap a span around the sentence like so:

HTML
<p>
   In medieval Italy, if a man was caught kissing a woman in public, 
   he had to marry her whether he liked it or not. 
   <span class="highlight">I guess kissing booths weren't very 
   popular back then.</span>
</p>

Just like with the div, I can use an id or a class to identify the span for styling. In this case I chose to use a class because it is likely that I will want to highlight other sentences somewhere else on the website.

When to Use Div and Span

The key thing to think about when choosing between div and span is where it is going to be used. Span should be used only for pieces of a whole (a sentence in a paragraph, a word in a sentence, etc.) Div should be used to group items together into a section. Some of you who already know a thing or two about styling are already jumping ahead of me and thinking about changing the style of div and span. For instance, you could make span act like a div, where it has a break before and after it or you could make div act like a span, where it does not have a break before or after it and it can be used in-line. Wouldn't that mean that these two items are interchangeable? Nope. You still cannot use block elements inside of a span, even if you make it act like a block element itself. You can use a div in-line but doing so breaks the intended purpose of a div.

The Box Model

The first thing we should discuss when talking about item layouts is the "box model". This is a term you will hear quite a bit when discussing CSS. It is most likely also going to be a source of frustration for you as you work on your layouts so it is important to understand and get right.

Each block element has a few items that contribute to its overall height and width. These include:

  • Content - this is the actual "stuff" in the block element. It could be the text in the paragraph or the image in the image tag.
  • Padding - the white space between the edge of the content and the border of the element.
  • Border - the border itself can take up space (for instance, if you want to draw a 1px-wide box around an element, this would add two pixels to the overall height and two pixels to the overall width (one pixel for each side).
  • Margin - the white space outside the border. This is the buffer zone between this element and others on the page.

Here is an illustration of how this works. You will see this diagram all over. Feel free to laugh at my drawing skills:

Image 1

That's great and it seems fairly straightforward but why is it important? Excellent question! Knowing the overall height and/or width is very important to making sure your elements line up correctly on the page. The first rookie mistake you will make is setting the height or width property in CSS and thinking that is the height or width (clue: it isn't). What you set is the height or width of the content. The actual element will be larger than that unless you specifically reduce the padding, margin and border height or width values to zero.

For example, if we wanted to place four pictures on the screen so that their edges touched, we would first place the HTML images on our page like so:

HTML
<body>
    <h1>Pictures Example</h1>

    <img class="promo" src="pic1.jpg" alt="counter" />
    <img class="promo" src="pic2.jpg" alt="table" />
    <img class="promo" src="pic3.jpg" alt="chair" />
    <img class="promo" src="pic4.jpg" alt="texting" />
</body>

We would then create a CSS rule for the promo class like so:

CSS
.promo {
    width: 240px;
    border-width: 0;
    margin: 0;
    padding: 0;
    height: 240px;
}

This would ensure that all four pictures had a total height and width of 240 pixels. However, this is where you start to pull your hair out a bit. Let's look at what this gives us when we run our web page:

Image 2

That's not right! If we look at this in page inspector (we haven't covered this yet - we will get to it eventually but for now, trust me) we see that the spacing worked as we expected but there is still that space between pictures. This is a product of the block element. To resolve the issue, we can change one extra property: the float property. If we make our element float, it eliminates the spacing between elements. To add this property to our CSS rule, we enter it like so:

CSS
.promo {
    width: 240px;
    border-width: 0;

    margin: 0;
    padding: 0;
    height: 240px;
    float: left;
}

We will get into float in more depth in a bit, but for now, this allows us to slide the elements up next to each other like so:

Image 3

That's what we were looking for. As you can see, sometimes even when you do it right, you get unexpected results. This is where patience, experience and a knowledge of how to diagnose issues becomes important. Don't get scared off, though. Not everything is difficult and ugly. For the most part, as long as you understand the box model, you won't have any issues.

Before we move on, I do want to point out that each of the properties we mentioned that add on to the content size (margin, padding and border) can be manipulated on each side. For instance, above we have set the margin to be zero but what if we wanted the right margin to be ten pixels? Not a problem. We can do this in one of two ways. First, we could specify the value for the four margins in one line like so:

CSS
margin: 0 10px 0 0;

The four values represent top, right, bottom and left margins respectively. Thus, I set the right margin to ten pixels by putting 10px in the second spot. Note that when you have a zero value, you do not specify units (zero is universal) but any other value needs to include the units. In most cases, we specify pixels.

The second way we could specify the right margin width is to specify it specifically like so:

CSS
margin-right: 10px;

This specifies just the right border width and it assigns it a value of ten pixels. There are properties for top, right, left and bottom. The difference between these and the one-line way we saw above is where we are setting the values. If we are setting all of the values in one CSS rule, we use the one-line method. If we are just setting one, two or three of the values but inheriting the other values from another rule, we use the second method.

You can use this top, right, bottom and left assignments for margins, padding and borders. This allows you to be very specific on how you want your item to look. For instance, you might want a thick blue border on the left side of an image but nothing on the other three sides. Or, you might want padding on the top and bottom of an element but not on the left and right sides. All of these actions can be handled through the CSS properties we have seen here.

The Float Property

We saw the float property earlier when we were looking at our images. Float allowed us to move our images directly in contact with each other instead of having a space between them. Let's look at float in a bit more detail so we know exactly why that worked and how we can use it in other scenarios.

The float property allows an element to float (now you are thinking you overpaid for this article, aren't you?) to the left or the right. For instance, if we wanted a picture to slide over to the right of the page, you could do that by adding "float: right;" to the CSS rule. In our case, we wanted all of the pictures to be on the left, so we set their float to be left.

This is a powerful feature of CSS that you will most likely be using in a number of scenarios. One of the cool things that can happen is that other elements work around the floating objects. For instance, you can put a paragraph of text around an image that is floating to the right like so:

Image 4

That's neat and it can give us some nice effects, especially since HTML pages adjust to the size of the browser. This allows our page to change without us doing anything. Unlike a print magazine where we are setting things up to be a precise layout, HTML adjusts so we need to use things that adjust along with the different resolutions that might be used. Float works great for that.

Now to the downside of float. Say you are using float for images that you want to be right next to each other. Then you want to put a paragraph of text below the images that describes the images. Your first attempt might be to make the images float left (so they all touch) and then just put a paragraph section after them. That should work, right? Well, let's look at what it could turn out like:

Image 5

That is exactly how we want it. Everything is great, right? Well, on our machine, yes. However, once we deploy the site, we are going to get calls about things not looking right. After putting down end users as "clueless of our greatness", we finally walk down to the cube of the user who is (needlessly) complaining and we see this:

Image 6

Whoops. What is going on? Are they on Netscape Navigator or something? Nope, they are using the latest version of Chrome. So what is it? Well, this is the downside of float. Sometimes you don't want things to wrap around your floating objects. Fortunately, the fix for this is fairly simple. We just need to clear the effects of our float on the paragraph. How do we make this magic, you say? Simple. You just add this to the CSS rule affecting your paragraph:

CSS
clear: both;

This clears the float effect on both sides of your paragraph. If you wanted to just clear the float effects from the images above but not the items below, you could say:

CSS
clear: left;

So, to sum up, you can float objects to move them around to the left or right in a dynamic manner. This affects other elements around them, so they can apply the clear property to nullify the effects that are being applied by floats around them.

The Display Property

The display property allows us to change how elements are displayed on the page. I hinted at this earlier when I said that span could be changed to act like a div and a div could be changed to act like a span. This is done through the display property. First, let's look at some of the options that we have for the display property and what they do:

  • inline - This makes the item act like a span, where there is no space above or below the element.
  • block - This makes the item act like a div, where there is space above and below the element.
  • inline-block - Everything inside the element acts like it is in a block but the element itself is put inline.
  • list-item - This puts items in a list (like this bullet list).
  • none - The element will not be displayed at all. This also means that the element does not affect the layout of the page at all (this is important).

So, if we want to not display an element at all, we add this to its CSS rule:

CSS
display: none;

If, instead, we want to make that span affect the layout like a div does, we would add this rule:

CSS
display: block;

Using different display options is one of the ways you can tweak your layouts to get the precise look you are going for while not changing what the document says about the content. We will get into this topic in more depth below when we discuss CSS Tables.

Besides the table options of the display element (which we will discuss below), the other major item I left off is the flex element. This is a display type that has been evolving over the past few years. The general idea is that the items inside the element flex to fill the space given. Support for this new CSS3 item is still coming, so be careful when you look to use it. Make sure that you know which browsers you want to support and then ensure that those browsers can use the property. One way to figure out what is supported and what is not is by going to the site CanIUse.com. This site tells you which features are supported by which browsers. It is an invaluable resource when working with HTML5 and CSS3.

The Align Property

Aligning items can be a bit messy until you get a good grasp on what the different options are and what they are intended for. When you think about alignment, you would think that it would be simple enough to have a property called "align" that has "left, right and center" as options. Nope. Instead, we have a number of different options based upon what we are trying to align. We have already discussed the float option to allow us to move elements around inside their container. Let's look at a few more options.

Block Elements

Block elements are already aligned. They take up the entire width of the page. However, maybe you want to set their width. By default, that element is then left-aligned. How do you change that to be centered? Like this:

CSS
.centered {
   width: 50%;
   margin-left: auto;
   margin-right: auto;
}

In this case, we used the margin-left and margin-right properties set to auto to center our item. If we wanted to right-align the element, we could omit the margin-right property. Let's make this even more complicated. Say this element is a h1 tag that has our title. If you look at it when it is "centered" on our page, it is going to look off. That is because while the element is centered and only taking up half the width of the page, the text inside is still left-aligned. That brings us to our next alignment option: text.

Text Elements

Text elements can be aligned using the text-align property in CSS. Your standard options are left, right, center and justify. These work just like the alignment option does in a text editor. Again, remember that block elements take up the entire width of the page. That means that if you right-align the text in a paragraph tag, it will align against the right edge of the screen (unless you changed the element's width). So, in our example above, if we wanted to center a h1 tag on the screen and center the text, we would update our CSS rule as follows:

CSS
.centered {
   width: 50%;
   margin-left: auto;
   margin-right: auto;
   text-align: center;
}

Absolute Positioning

This is the big gun of positioning and it should be used with care. Normally HTML pages are dynamic in that they adjust to the size of the window that they are being displayed in. However, there are times when you want an element to always be in a specific spot no matter what. Maybe you want your logo to always be in the lower right of the screen. To do this, you would create a rule similar to this:

CSS
.logo {
    position: absolute;
    right: 0;
    bottom: 0;
}

First, we set the position to absolute. That turns off the adjustments that are made based upon screen width, things around the element, etc. Next, we set the bottom and right properties to zero. What this does is says that we want it to be zero pixels from the right edge and zero pixels from the bottom edge. As a result, you could use the left instead of the right to put the logo in the bottom left.

Be careful when using positioning like this. It can cause unexpected or undesired effects when viewed in different browsers or at different resolutions. In general, don't fight the dynamic nature of HTML. Instead, embrace it and work inside the system.

Lists

In a previous article, I went over unordered lists and ordered lists and how we could then modify them using CSS. We also saw in display section that we can change an element to act like it is in a list even though it is a div, for example. As we will see in the CSS Table section, there are two sides to HTML - the side humans see and the site computers see. Lists allow us to group things together in a hierarchy that can be read by computers and at the same time can be significant for humans as well. One use for a list is site navigation. The list lends itself well to the parent-child-sibling relationships in a menu. Here is an example:

HTML
<ul>
    <li>Food
        <ul>
            <li>Hamburgers</li>
            <li>Hot Dogs</li>
        </ul>
    </li>
    <li>Snacks
        <ul>
            <li>Popcorn</li>
            <li>Pretzels</li>
        </ul>
    </li>
    <li>Drinks</li>
</ul>

Note that under food there is a sub-menu. The same is true for snacks but drinks does not have a sub-menu. You could then utilize CSS to style this list into a menu. There are a lot of options that you can use to modify elements and addressing them all is outside of the scope of this article. To get you started, though, look into adding the following properties to your CSS rules:

  • list-style-type: none; - This takes off the bullets or numbers that are typically associated with a list. Put this on your ul or ol element.
  • display: inline; - This converts your vertical list into a horizontal list. Put this on your ul or ol element.
  • width: 240px; - This size is up to you but setting a standard width ensures that your menu options are uniform. Put this on your li elements.
  • border: 1px solid #000; - This gives all of your elements a defined border. Put this on your li elements.
  • background-color: #b6ff00; - This gives all of your elements a background color to help them stand out. Put this on your li elements.

CSS Tables

Early on we learned about HTML tables and how they should not be used for page layouts. The reason for this is because a table element tells the browser something about the data. It says "this is a spreadsheet of data" to the browser. Unless you are putting a baseball player's stats in a grid, or something similar, you probably should not be using a HTML table to lay out the items on the page.

The problem is that sometimes you want items to lay out on the page like they were in a table. What do we do then? Well, in comes the CSS table. We can use our display property (remember that one from above?) to identify our div elements as the different parts of a table. The values we use for the display property in CSS are:

  • table - this is what wraps the entire table (I just blew your mind there, didn't I)
  • table-row - this is what wraps an entire row in our table
  • table-cell - this is one cell in a row
  • table-row-group - this groups all of the data rows together (the body of the table)
  • table-header-group - this groups all of the header rows together

There are other tags that you can use that are for more advanced cases but these are the primary tags you will be using. Each one turns a div into the layout equivalent of its table counterpart. Let's see how we would set this up. First, let's look at the CSS:

CSS
.container {
    display: table;
}

.header-section {
    display: table-header-group;
}

.data-section {
    display: table-row-group;
}

.row {
    display: table-row;
}

.data-item {
    display: table-cell;
}

This creates five CSS class rules for us. Now we can use that in our HTML to set up our table like so:

HTML
<div class="container">
    <div class="header-section">
        <div class="row">
            <div class="data-item">Item</div>
            <div class="data-item">Price</div>
        </div>
    </div>
    <div class="data-section">
        <div class="row">
            <div class="data-item">Hamburger</div>
            <div class="data-item">$5.50</div>
        </div>
        <div class="row">
            <div class="data-item">Hot Dog</div>
            <div class="data-item">$4.75</div>
        </div>
    </div>
</div>

Now we have the layout of a table without actually using a HTML table. Why is this important? Well, remember that a HTML table tells the browser something about the data it contains. A CSS table does not tell the browser anything except "lay these sections out like this". It may seem like a small difference, but it is important. Modern web design is aimed at two different audiences: humans and computers. To the human user, the HTML table looks no differently than the CSS table. However, to the computer viewer (web crawlers, screen readers, etc.) the HTML table is radically different than the CSS table.

Conclusion

That's all there is too it. Simple, right? Well, maybe not. We did cover some tricky topics in this article. Laying elements out, especially on a page that will be viewed at different widths and in different browsers can be difficult at times. However, if you concentrate on the basics we learned here and if you think through what the browser is doing, you will be fine.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)