A Web page's layout describes the positioning of all of the content blocks. This includes how much space exists between each block, as well as the width and height of all of the elements. This can all be controlled using CSS.
Creating a modern and functional layout is perhaps the most challenging operation done with CSS. It could fill at least a semester of training to learn all of the tricks, quirks, and design trends that are required in order to make a passable Web page layout to today's standards.
A good place to start is by understanding the foundation of all CSS layout, which is the box model in CSS.
Understanding the Box Model in CSS
All elements in the browser reside within a series of boxes, whether the elements are block or inline elements.Their basic behavior is defined in the box model of CSS, which states that there are three rectangular layers that surround the content area of an element.
An element is not just the text or image applied between tags. CSS draws an imaginary box around elements and applies rules to that box in a number of ways: as a whole, to the foreground or background of the box, to the edge of the box, and to the space both inside and outside the box.
As the diagram shows, the element itself is at the very center of the box. A border surrounds the element. This border can be pulled flush up against the element or space can be added between the element and the border. This space between the element and the border is called padding. Space can also be controlled between the borders of neighboring elements. This space is called margin.
The box model is entirely controllable using CSS. The function of the element box is to describe the amount of space that an element may occupy in a document in relation to other elements. And that means the size and position of an element box influence the size and position of other elements.
Understanding Box Width
Every element has a width. The width of an inline element depends on the amount of content in it, and the width of a block-level element is 100% the width of its parent by default.
Changing the Aside Box
We have already added a 1 pixel wide border area to all sides of our aside element, and we will continue to use the aside to demonstrate the box model.
To more clearly illustrate the box model and how it pertains to CSS layout, we will first assign width and float properties to the aside.
We can override these defaults by explicitly defining a width using CSS.
Let's add a width equivalent to the width of the image (265 pixels) inside the aside, so as to make the aside better conform to its primary content. This will also make the border appear more tightly around just the content.
Step1. To change the box width of the aside element, type:
aside {
border: 1px solid black;
width: 265px;
}
footer {
Exiting code block
Step2. Save and refresh index.html.
Calculating Computed Box Width Properly
We have assigned a 265 pixel width to our aside, but it is important to consider the layers of the box model, and their relationship to the box's entire width.
When we use the CSS width property on an element, it defines the width of the content area, not including the padding, border, or margin. The computed width of the element is a sum of the width and left and right padding, border, and margin.
This means that even though we gave our aside a width of 265 pixels, it is actually at least 267 pixels wide after the 1 pixel wide border on each side of the element.
Using Shorthand Syntax for Box Properties
The padding and margin properties, like the border property, are shorthand CSS properties. However, instead of implicitly declaring twelve properties, padding is only shorthand for four properties, namely the padding-top, padding-right, padding-bottom, and padding-left properties. The margin property works in the same way.
Additionally, padding and margin can be given multiple values, much like the border property. Declaring one value assigns the value to all sides of the box; two values assigns the top and bottom with the first value, and the left and right the second value; three values assigns the first value to the top, the second value to the left and right, and the third value to the bottom; and finally, four values assigns each to the top, right, bottom, and left, in that order.This is illustrated in the diagram below:
Now when you peek at other designer's stylesheets, you'll better understand what they are doing with their padding and margin properties.
Let's use this method now.
Understanding Padding
The content looks a bit cramped within the aside element. We can add a bit of space between the border and the content by using the padding property in CSS.
We want to apply the same padding across the entire box, so let's just assign one value. We'll use ems, so that the space will scale with the font size, which will keep the layout more consistent-looking in the event the font size changes.
Step1. To apply a 0.5 em padding on all sides of the aside, type:
aside {
border: 1px solid black;
width: 265px;
padding: .5em;
}
Exiting code block
Step2. Save and refresh index.html.
NOTE: To compute the pixel value of 1 em, we have to consider the font size in the aside's context. Going up the ancestor line, we find that the default font size is only modified at the global body element level, which assigned a value of 110%. Since the default font size is almost always 16 pixels, the value of.5 em is 16 times 1.1 times .5, which is 8.8 pixels.
Understanding Normal Document Flow
Understanding normal document flow is the first step in grasping the effects positioning creates for how a Web page is displayed. Normal document flow of a document is its unpositioned state. Put simply, it is how the Web browser manages the document content by default. If you view our document in a Web browser right now, you will notice that the layout of the individual sections is dictated according to the normal content flow. Normal flow works with the principles of block andinline boxes. A block box is the principal box generated by a block-level element, which is an element that is visually formatted as a box and typically begins a new line. Inline boxes are placed horizontally in a block box and begin where they occur in the larger block. Unlike the block boxes, they are not separated in the normal document flow with a new line.
A block box is made up of a containing block and its descendant block boxes. A containing block is the surrounding block where the general formatting and positioning take place. In most cases, the containing block corresponds to the parent element.
While the block and inline boxes determine the normal document flow, the containing blocks play a critical role in controlling the document flow. Any type of control exercised over the document flow will be defined in relation to the position of the particular element box within the containing block.
Controlling the Document Flow
The normal document flow is often unsatisfactory in terms of designing a Web page which requires both a functional and a visually pleasing layout. In order to accomplish this ideal layout, CSS offers several ways to enable Web developers to exercise more precise control over the document flow, selectively changing it to suit the desired layout goals.
Let's explore one of the more commonly used ways now.
Understanding Float
Having the 265 pixel width, the aside might look a bit awkward because of how it sits above the rest of the content. Since the element is called an aside, it might make more sense if it were to sit on the side of the Web page. We can achieve this with a float property.
The float property tells the element to sit on the left or right side of the parent container, allowing all of the other content below the element to flow next to it. Floating content removes it from the normal document flow.
Let's try this out now.
Step1. To position the aside to the far right, type:
aside {
border: 1px solid black;
width: 265px;
float: right;
padding:.5em;
}
Exiting code block
Step2. Save and refresh index.html.
NOTE: It is recommended that you always assign an explicit width to any element you will float. Furthermore, floats should not be used on inline elements, as it may result in very unexpected results in different browsers.
Changing the Aside Margin
As we look at our page, it may appear that the content outside the aside is encroaching a bit close to the aside's border. We can mitigate this by changing the margin surrounding the aside, which will push the surrounding element boxes a little further away from the aside's box.
Let's apply the same value of margin to the aside that we did for the padding.
Step1. To apply a.5 em margin on all sides of the aside, type:
aside {
border: 1px solid black;
width: 265px;
float: right;
padding:.5em;
margin:.5em;
}
Exiting code block
Step2. Save and refresh index.html.
Incorporating Background Images
We have already filled the background of the nav element with a solid color, but we also have the ability to place an image behind content using CSS. When we apply a background to an element, it spans the entire padding area. However, unlike the padding or border areas, margins are always transparent.
In order to make our header look more prominent, we will assign it a background image. Since the Equinurture service involves horses and nature, we will be using a graphic of grass.
The background-image property is what is used in order to apply an image to the background of an element.
Creating a Tiled Background
The background image renders from the top left corner of the element by default. If our element is larger than the background image applied to it, then the image will automatically repeat or tile as necessary to fit the entire element.
The grass image is one that only draws a few blades of grass, so the default repeating behavior of background images will work nicely for header.
The syntax for the value of the background-image property is where url is written, followed by the absolute or relative path to the final name within a set of parentheses. The grass image is in the images folder, so we will be using a relative address to it.
We currently have rules header h1 and header p whose selectors descend from header, but we want this background to appear behind the entire header's box, so we will need to first make a rule that targets just header.
Step1. To add a background image to our header, type:
color: #343434;
}
header {
background-image: url('images/grass.png');
}
header h1 {
Exiting code block
Step2. Save and refresh index.html.
NOTE: Concerning the quotes in the file path above, url(images/grass.png) and url("images/grass.png") are also both syntactically correct values for the background-image property. However, using double quotes interferes with inline style, due to the HTML attribute syntax. Omitting quotes altogether makes it more challenging to handle file names with spaces or parentheses.
Resizing the Header for a Background Image
Unlike image elements, background images do not push content around in order to fit. Instead, a background image will be cropped if the element is too small to encapsulate the entire image file's dimensions.
So far, the height of our elements have been purely dictated by the content sitting inside them. We can explicitly set a height to an element using the height property in CSS.
In order to see the whole height of the background image, we will use the height property on our header element. We will set its height to easily accommodate the height of the grass image, which is 180 pixels tall. Since background images only apply to the content and padding areas by default, setting a height that is slightly shorter than the image file gives us some safe space in case our element expands a bit from unforeseen circumstances.
Let's set the height to be the actual image height (180px), minus some safe space (-10px), so the value we will use is 170px.
Step1. To increase the height of the header element, type:
header {
background-image: url('images/grass.png');
height: 170px;
}
Exiting code block
Step2. Save and refresh index.html.
Cleaning Up Positioning
We have completed the basic style and layout of the Web page. On the other side of this milestone is fixing up some sizes and awkward spaces lurking about.
Touching Up the Header Content Styling
The placement and size of the text in our header could use a little work. Since art is in the eyes of the beholder, feel welcome to tinker around with any of these settings.
Touching up the Heading 1 Element
The main heading in our header could afford to be a bit larger, and have a little more space around it.
Step1. To change the font size for the main heading, type:
header h1 {
color: sienna;
font-size: 46px;
}
Exiting code block
NOTE: Despite having relative units for all the rest of the font sizes in the document, having a pixel-based measurement for the main heading isn't necessarily "bad." In this case, we may want to keep the font relative to our header size, which is measured in pixels.
Step2. Save and refresh index.html.
Step3. To re-position the main heading's element box, type:
header h1 {
color: sienna;
font-size: 46px;
padding:.25em.5em 0;
margin-bottom: 0;
}
Exiting code block
Step4. Save and refresh index.html.
Touching up the Tagline Paragraph
The tagline paragraph could use a bit of positioning work; it is hugging the left side of the header, and it is still a bit too far from our heading 1 element. We can tackle both of these problems with a single margin property declaration.
The shortest way to remove the top margin and add a left margin is to use the two value margin property syntax. The first value sets the top and bottom margins, and the second value sets the left and right margins.
Step1. Locate the header p rule.
Step2. To re-position the tagline paragraph, type:
header p {
font-style: italic;
margin: 0 2em;
}
Exiting code block
Step3. Save and refresh index.html.
NOTE: Keep in mind that we also set our right and bottom margins. It isn't a problem in this case, since we don't have anything touching the right or bottom edges of the tagline paragraph. However, using the two-value syntax in other situations may cause problems. Resolving those may require using the more explicit three- or four-value syntax.
Moving the Sections in from the Article Margin
This page might look a bit better if the content in our main sections sat a bit further away from the edges of the Web page. We can do this by adding a padding to the left and right sides of the article element, which acts as a container for the two sections. Modifying the padding of the wrapper element will impact all of its children elements.
The two value syntax will come in handy again, so we avoid having to write two different declarations to apply a left and right margin.
Let's go for 1em away from the sides.
Step1. Place the cursor on a new line immediately above the aside rule.
Step2. To shift the wrapped elements within the article element, type:
color: #ccccff;
}
article {
padding: 0 1em;
}
aside {
Exiting code block
Step3. Save and refresh index.html.