How to Position Elements in CSS
 
 

Positioning Elements in CSS

In old style CSS, it used to be difficult to specify location of elements within a page. Your only option was to use tables, which were cumbersome and difficult to use. Now, "tableless" designs are used, which basically means websites use div HTML tags along with layers to set the position of these elements. Tableless designs and layering pages have been around for several years, but CSS has helped with designing the location and dynamic sizing of these elements. In this article, we'll learn how to work with tableless designs, position elements, floating styles, margins and padding, and other aspects of creating layouts that fit a page width and height.

Tableless Website Design

When you work with website designs, you'll often hear about tableless CSS. Years ago, tables were used to format the way a web page displayed items. You started with one table, and then each table cell contained the elements you wanted to format. The table cells were set with a width, height and the table given a position within the main table container. This became tedious for developers, and the table layout design was traded for div containers.

 The div container acts as a table except CSS is used to control the positioning of the div tags instead of relying on the browser's table control.

By default, div tags are positioned in what is called the "static" position. The following CSS and HTML show you a default tableless design with three div containers.

div {
    position: static;
}

<!DOCTYPE html>
<html>

<head>

<link rel="stylesheet" type="text/css" href="/mystyles/styles.css">

<title>This is my first web page</title>

</head>
<body>

 

<div id="container"> This div is the main container.

            <div id="div1"> This is div one. </div>

            <div id="div2"> This is div two. </div>

            <div id="div3"> This is div three. </div>

</div>

</body>

</html>

All div containers in the above code are set by the defaults of the browser. This means that the div containers will line up in a row and automatically wrap.

Since static positioning is the default, you don't need to specify it. However, you won't normally use static positioning. Instead, you'll normally use the other common positioning values, which are relative, absolute, fixed and you can also inherit a position from a parent container.

Relative and Absolute Positions

The two most common positioning you'll use are relative and absolute. Relative positioning sets the location of a div to the location of its parent container. For instance, if the parent container is in the middle of the screen, setting a div container to 50 pixels from the top of the parent, the div will be 50 pixels from the top of the parent, which is 50% from the top of the screen. This is difficult to imagine when you try to visualize it. The following code shows you an example of how you would use this type of positioning.

div.container {
    position: static;

    top: 100px;
}

div.div1 {
    position: relative;

    top: 50px;
}

<!DOCTYPE html>
<html>

<head>

<link rel="stylesheet" type="text/css" href="/mystyles/styles.css">

<title>This is my first web page</title>

</head>
<body>

 

Interested in learning more? Why not take an online CSS course?

<div class="container"> This div is the main container.

            <div class="div1"> This is div one. </div>

</div>

</body>

</html>

In the above code, the main container, named "container," has a static position on the page 100 pixels from the top of the screen. The second div, "div1," has a relative position 50 pixels from the top of its container. Since the container is the "container" div, "div1" is actually 150 pixels from the top of the screen. Try it out yourself to view the results.

Absolute is a bit different from the relative positioning property. Absolute lets you "remove" an element from all the containers and manually set its positioning. In other words, you might have a div container several levels into the HTML, but you want to set its placement regardless of its parent container. You do this with the absolute position. We can use the same HTML and CSS as we used with the relative example. Take a look at the CSS and HTML below.

div.container {
    position: static;

    top: 100px;
}

div.div1 {
    position: absolute;

    top: 50px;
}

<!DOCTYPE html>
<html>

<head>

<link rel="stylesheet" type="text/css" href="/mystyles/styles.css">

<title>This is my first web page</title>

</head>
<body>

 

<div class="container"> This div is the main container.

            <div class="div1"> This is div one. </div>

</div>

</body>

</html>

In the above example, the only code that's changed is the positioning of div1. Div1 is now set to absolute. Now, it does not matter where the "container" or parent div is located. Now, the browser places div1 50 pixels from the top of the screen regardless of its container. So, you now have the "container" div located 100 pixels from the top of the page and div1 is 50 pixels from the top of the page.

Finally, the next common positioning is the "fixed" property. Fixed works similarly to the absolute position element. The only difference is that fixed is a position relative to the main document and scrolling does not change the position. For instance, if you need to create a navigation menu item that does not leave the page when the user scrolls down the browser screen, you would use the "fixed" position value.

Positioning and Float

Just like print layouts, wrapping text around an image makes your web pages much more attractive and easier to read for users. You can use the "float" CSS property to set image locations and how text will wrap around the image. You can also use "float" with div elements. For instance, you might want to use a div container for an image and then set the text to float to the left or right of the image div. It should be noted that the value you give the "float" property is the container itself and not the text. Take the following CSS and HTML as an example.

div.container {
    position: static;

    top: 100px;
}

div.div1 {
    float: right;
}

<!DOCTYPE html>
<html>

<head>

<link rel="stylesheet" type="text/css" href="/mystyles/styles.css">

<title>This is my first web page</title>

</head>
<body>

 

<div class="container"> This div is the main container.

            <div class="div1"> This is div one. </div>

            This text will show to the left of the above div tag.

</div>

</body>

</html>

In the above code, the same CSS is used as the previous samples in this article except the float property is used. The float property for div1 is set to float to the right. This means that div1 stays to the right of the container and the text within the main container div wraps to the left. If you set the float property to "left," the div1 container would stay to the left and the text would wrap to the right. Remember that the float property sets the div or image location and the text wraps to the opposite side.

Margins and Padding

The difference between margins and padding are subtle. We spoke of margins and padding in previous chapters, and in most respects they are similar when you use them separately. However, there are some differences between margins and padding when you define actual spacing between elements within a container and elements outside a container.

Margins are like margins you consider on a page. Margins are the surrounding space between the element and other elements. Padding is the spacing within the container or within the "border." For instance, if you set padding within a div container, the text is spaced within the container based on the padding value. With a margin, text or elements outside of the div's border are spaced based on the value of the margin property.

The following CSS shows you how to set a margin and a padding value for a list.

li {
    padding: 10px;
}

ul {
    margin: 10px;
}

Note that the above code sets padding for the <li> HTML tag, which is the tag that sets list items if you recall from previous chapters. The <ul> tag indicates that the list is an unordered list.

In this CSS, the padding for the <li> tag is set to 10 pixels. This means that each item will have 10 pixels between them. The <ul> tag has a margin set. This means that any text, divs, images or any other HTML elements will have at least 10 pixels between their borders and the unordered list's border. If the other elements also have a margin set, then the spacing will exceed 10 pixels. For instance, if an image has a margin of 10 pixels and the list has a margin of 10 pixels, a total of 20 pixels will be spaced between the two elements.

You'll find that positioning and spacing are always needed in a website design. The best way to troubleshoot or test your code is to open it in a browser. Test the results and change the positioning values until you get the desired results. Positioning is probably one of the most tedious and time consuming parts of design, but as you test and change values, you'll soon get each HTML element in the right position until you finish your design.

Validating CSS and HTML

After you finish your CSS and HTML design, you need to validate it in some way. There are several validation tools on the market across the web. The official validation service is offered by w3c.org, which is the World Wide Web Consortium. This organization publishes the standards for HTML markup from the beginning of HTML 1.0 to the current HTML 5 markup. You can use the w3c.org validator to check your markup, but you must be able to identify errors and fix them as the validator finds them.

You should work to have markup that is as close to perfect with no errors. Every developer tries to create markup with no errors, although even the biggest corporations have validation errors. Run Google through the validator, and you will find markup errors. Even with markup errors, your pages will render for most browsers, especially modern browsers. Search engines can read through most markup errors as well.

So, Why Validate Your CSS and HTML Code?

You might wonder why you should bother with validation if most browsers and search engines can read the invalid markup. The issue isn't usually with modern browsers or even search engine readability. Instead, the issue lies with cross-browser support and ensuring that users are able to view your web pages regardless of what code or content you use. Like most website owners, you probably want to reach the widest audience and coding errors limits that audience.

Older browsers are the biggest issue. Older browsers don't work through many coding errors, so you can lose viewers with older browsers. Validating your markup also makes your HTML and CSS code future browser proof. This means that browsers created tomorrow that have backward compatibility (as most browsers have) will be able to read your code. If you coded your web pages today and validate it as error-proof code, you guarantee that browsers created 10 years from now with backward compatibility of older HTML versions will be able to render your code.

Search engine visibility is another issue. While search engines can work through errors, search engine companies seek to rank websites that have the best user experience. If your code is broken and can't be rendered with older browsers, how good is your user interface? Does your site offer good readability and user engagement if it doesn't work with all browsers? If your site does not offer cross-browser support but your competitor's site does, whose site should rank higher? For the most part, search engines will understand broken code that does not validate, but user engagement is a ranking factor, and therefore your site should offer code that runs in as many browsers as you can. Most importantly, your site should run in Safari, Chrome, Firefox and Internet Explorer.

The only way to truly test your code is to run it in each browser. This can be done on different machines or running virtual machines with different browser versions. Some websites offer emulators that run code in older browser versions, but you can also test code on your local machine. You can also ask friends and family with older computers and browsers to run your website and let you know if they see any errors. In addition to testing in different browsers, you must also cover different operating systems. This means you must test your code in Mac's OS, Windows, and several distributions of Linux. This can be a tedious requirement, which is why some companies and even small website owners ask a tester to run code and tests against the website. The more browsers you test, the better reliability your site has with a broad audience and viewership.

DocType and Validation

The DocType you set has a big influence on your HTML and CSS validation. If you remember from previous chapters, we discussed DocType and how it should be set for HTML 5 code. If you have the wrong DocType set, your code will not validate. The w3c.org site lists the different DocType tags for each version of HTML. HTML 5 has the simplest DocType tag you should implement, but if you accidentally type out the wrong DocType, your validation will fail.

Always check the type of DocType you've entered before you panic with your code. For instance, if you have the HTML 4 DocType set and you use tags that are only available in HTML 5, validation will fail. We covered some HTML 5 only tags in earlier chapters. These tags will not work in older versions of HTML.

Validation and Editors

Editors that create HTML and CSS for you on-the-fly are one common reason for validation errors. Editors such as Dreamweaver create errors in code just from its automation. Be careful when you use these tools, because sometimes they insert accidental coding errors that would not be there if you manually typed out HTML.

These errors are usually introduced when you use coding editors for dynamic languages. When you render HTML based on dynamic input, you sometimes output invalid HTML. The only way to remedy this situation is to check your dynamic code. Some common dynamic coding languages are C#, PHP, Classic ASP, VB.NET and Python.

Other types of code generators can cause validation errors. For instance, Wix and Weebly are great tools for new webmasters who are unfamiliar with coding standards and how to use CSS. However, these generators create code on-the-fly based on the input from the webmaster. This code generation can often create errors if you don't check to make sure the generator creates valid code. You can use thissectionto verify that the CSS and HTML generated is a part of the latest HTML 5 standards.

Validating your code is a tedious chore sometimes, especially if you coded a large site and don't have much experience in website design. Run your code through the w3c.org code validation generator to ensure that your code meets current standards and check to make sure the DocType matches they HTML version you've coded on your site. If you find any errors, the w3c.org validator will give you suggestions on what can be wrong with the code to help guide you through the issues. If your code does not validate 100%, it's not a critical issue as long as you've tested your code in the most common browsers and operating systems.