List of Articles in Series
- Writing your First Code
- Building on the Basics
- Styling Your First Web Page
- Laying Out Your First Web Page
Introduction
In the last part you saw how to mark different parts of your content according to its role. Now we will start to learn about how to visually format that content using CSS. However, just before we start I want you to remember the most important thing about HTML. HTML is for content! Why am I pushing that point so hard? Because I'm not the only one you will learn HTML from, there are an immense amount of tutorials for HTML, and while a lot of them will teach you short-cuts that are very comfortable, they may also be very problematic. So for your entire HTML journey I want you to remember HTML's role and stick to it. In the long run your life (as a developer) will look much better if you do so.
A Bit More HTML
The HTML document in this listing is the base of our tour today. I will use this document over the course of the article and show you how to make it look much better using CSS only.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Me Blog</title>
</head>
<body>
<header>
<img src="me.jpg" alt="me" width="150" height="150">
<aside>Kornfeld Eliyahu Peter</aside>
<h1>Me Blog</h1>
</header>
<article>
<h2>Fusce vel dolor sollicitudin</h2>
<p class="publish-date">12-03-2014</p>
<section>
<h3>Praesent sit amet</h3>
<p>Nam faucibus mi nec mauris pharetra iaculis. Integer quis facilisis velit. Donec aliquet purus a ante convallis sodales. Aliquam erat volutpat. Morbi sed lacus ullamcorper, ultrices lectus ac, suscipit mauris. Interdum et malesuada fames ac ante ipsum primis in faucibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent rhoncus scelerisque dolor id facilisis. Integer a vestibulum sapien. Vestibulum rutrum quam ultrices suscipit facilisis.</p>
<p>Pellentesque id bibendum dolor. Donec id ipsum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec rutrum pellentesque velit, sit amet cursus quam interdum non. Aliquam erat volutpat. Vestibulum accumsan ante quis lorem dictum, non posuere massa commodo. Praesent eu urna eget ligula viverra tempor. Duis porttitor quam eu dictum tristique. Morbi convallis sapien lacus, sit amet fermentum ipsum ultrices sit amet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In ut dolor pharetra magna ullamcorper dictum. Praesent sed nisl laoreet, convallis diam id, ultricies arcu. Donec non tellus lobortis, placerat nibh eu, tempor nisi.</p>
</section>
<section>
<h3>Vestibulum vestibulum</h3>
<p>Integer tempus metus sed tortor lacinia, et posuere risus feugiat. Donec dignissim eu libero id blandit. Quisque tristique faucibus elit nec sodales. Proin pellentesque euismod nisl, ut porta felis euismod commodo. Proin luctus, erat eget rhoncus elementum, est lectus accumsan nulla, id gravida tellus dui vitae nisi. Integer adipiscing placerat mi, in placerat erat consequat bibendum. Donec facilisis, felis eget dignissim accumsan, nisl turpis tempus purus, et faucibus est libero quis massa. Morbi vitae nibh convallis, varius est vestibulum, hendrerit ligula. Vestibulum at euismod dui. Duis nec ornare lectus. Nulla id lobortis turpis. Duis in lacus turpis. Suspendisse at tortor a lorem ornare tincidunt nec id nibh. In facilisis, est ac scelerisque ultrices, odio metus sollicitudin mi, non venenatis nulla nunc sed erat.</p>
</section>
</article>
<article>
<h2>Fusce aliquet augue</h2>
<p class="publish-date">01-01-2014</p>
<section>
<h3>Phasellus in erat </h3>
<p>Proin ultrices massa nec arcu ultrices hendrerit. Cras facilisis rhoncus risus, vitae dapibus tellus laoreet sed. Quisque in diam aliquam nulla accumsan fringilla. Vestibulum non imperdiet turpis. Cras lacinia enim diam, vel porta lorem malesuada eget. Nullam condimentum facilisis est non consectetur. Vestibulum interdum erat vitae facilisis luctus. Curabitur feugiat velit non lacus accumsan, quis vulputate elit ultricies. Maecenas eu orci mauris. Phasellus at vehicula odio, in accumsan diam. Nam luctus pellentesque tortor quis volutpat. Suspendisse non dolor libero. Nulla facilisi. Etiam sodales magna in justo fermentum, ut congue nisl tempus. Morbi egestas lorem nibh, auctor interdum erat congue quis. Morbi rutrum orci est.</p>
<p>Integer in dolor nec odio accumsan euismod. Nam adipiscing nisi sed mauris interdum posuere. Sed ullamcorper sollicitudin odio ut malesuada. Praesent euismod ac justo at volutpat. Sed venenatis mauris in imperdiet ullamcorper. Donec id ante sit amet augue iaculis aliquam. Quisque facilisis lorem elit, in pretium felis accumsan nec. Nulla interdum lacinia nunc, eget aliquam quam ultrices nec. Nunc eu leo lectus. Phasellus gravida nibh at elit ullamcorper lacinia. Etiam pretium, dui consectetur suscipit ornare, mauris massa hendrerit enim, ac facilisis ante nulla at dui. Etiam dictum accumsan metus in scelerisque.</p>
<aside>Etiam consequat risus sed lorem sagittis tincidunt. Nulla dolor purus, congue eget.</aside>
</section>
</article>
<footer>
<p id="cpy">Copyright © Me, 2014</p>
</footer>
</body>
</html>
Without any CSS the page looks like this:
Add CSS to HTML
In the previous part I wrote about how to link CSS to HTML document, but let me refresh your memory.
<link rel="stylesheet" type="text/css" href="style.css" />
This line - in the head of the HTML document (se above) tells the browser to use the style.css file as the stylesheet for visual rendering.
HTML Global Attributes
You may have noticed that I used two attributes I've never mentioned before. You already learned that HTML tags can have different attributes - like src
and alt
for an IMG
tag. Every tag has its own set of attributes according the role of that tag. However, there is a group of attributes called HTML Global Attributes, that can be applied to any HTML tag.
In that group of attributes there are two that have special meaning for CSS:
id
is an attribute that used to assign a unique identifier to any HTML tag. class
is an attribute that used to classify the HTML tag. Any HTML tag can have zero or more class names.
Using the Code
The attached code is exactly the one I used in this article. There is a page.html and all the images, the only difference that the style.css is empty (there is a final.css that has the final content). What I want you to do is fill the style.css according to what we learned to ensure that you understand better.
What In a CSS File
A CSS file can contain one or more CSS rules and CSS rules are composed of a selector and the declaration body. Each declaration in the declaration body is composed of an attribute name-value pair, separated by a colon (:). Between declarations there is a semi-colon (;) as separator.
selector {
attribute-name: attribute-value [attribute-value [...]];
[attribute-name: attribute-value [attribute-value [...]];]
}
Simple Selectors
- * is the universal selector. This selector will select all the HTML tags in your document. I advise you against using this selector. There is a performance issue with it and you will learn that there is no need for it, really.
- Tag selector will select all the HTML tags that match. For instance,
h2
selects all the second level heading tags. - Id selector is used to select a single tag (as id should be unique). To use this selector you have to precede the tag's id value with a hash (#) character. Id selectors are case sensitive - it has to be written exactly as it was in the HTML document. In our case #cpy will select the paragraph at the end of the document (the one with the copyright message).
- Class selector is used to find all the HTML tags that had been classified with that specific class. To use it you have to precede the class name with a dot (.) character. Class selectors are case sensitive - it have to be written exactly as it was in the HTML document. In our case
.publish-date
will select both the paragraphs with the date inside them.
Selector Groups
To simplify CSS files, you may want to group selectors together. For instance, you want to assign the same font to all the heading tags (H1-H6) or the same background color for paragraphs (P) and top level heading (H1), you can create sorter CSS by grouping the selectors together:
h1, h2, h2, h3, h4, h5, h6 {
font-family: sans-serif;
}
h1, p {
background-color: #f90;
}
Let's see all the grouping options:
Definition
| Explanation
|
selector1, selector2
| selector1 and selector2
|
selector1 selector2
| selector2 that is a descendant of selector1
|
selector1 > selector2
| selector2 that is a child of selector1
|
selector1 + selector2
| selector2 that is immediately after selector1
|
selector1 ~ selector2
| selector2 that is preceded by selector1
|
Attribute Selectors
These additions to the selectors can be used to check the existence and the value of the attributes assigned to the HTML tag.
Definition
| Explanation
|
selector[attribute-name]
| attribute exists
|
selector[attribute-name="value"]
| attribute with exact value
|
selector[attribute-name~="value"]
| attribute that contains value in whitespace separated list
|
selector[attribute-name|="value"]
| attribute that begins with value followed by ”–”
|
selector[attribute-name^="value"]
| attribute that begins with value
|
selector[attribute-name$="value"]
| attribute that ends with value
|
selector[attribute-name*="value"]
| attribute that contains value
|
For instance, writing .publish-date
and [class="publish-date"]
gives the exactly same results in our HTML document.
The attribute-name part is one of the over 150 attributes that supported by CSS. We will see some of those attributes in a few moments. According to the selected attribute the value part can contain one or more values separated by space.
There is a large number of possible CSS attributes, in this article I will cover attributes related to background, text and font.
CSS Rules Priority
I mentioned it in the first part, how repeated CSS rules are interpreted (and I mean what happens when more than one CSS rule is fitting the same tag). Remember the rule is precedence, what is newer (comes later in the CSS file) will be used! For example, in the sample below the paragraph text will be green...
body p {
color: red;
}
article p {
color: green;
}
Background Attributes
Background in CSS can be defined in two ways. One is color, and the other is image.
Color Attributes
To colorize the background of an HTML tag we can use the background-color attribute.
CSS uses colors from the RGB color space, which means that any color is defined according its red, green and blue components. Colors also can be selected from the HSL color space, where colors are defined by hue, saturation and lightness. There are four ways to define the actual color:
- Using pre-defined names: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, and yellow.
- The
transparent
keyword. - Using the numeric notation: #rgb or #rrggbb. The values are in hexadecimal form and can be between 0 to f or 00 to ff. For instance, red can be written as #f00 or #ff0000 too, but orange can be written as #ffa500 only.
- Using the color functions:
- rgb(r, g, b) or rgb(r%, g%, b%).
- rgba(r, g, b, a) or rgb(r%, g%, b%, a%), where a is for alpha blending - means opacity of the color
- hsl(h, s, l) or hsl(h%, s%, l%)
- hsla(h, s, l, a) or hsla(h%, s%, l%, a%), where a is the same as before
Now let's colorize our blog page. As a first step we will colorize the three main parts of the blog - header, article and footer. Open up the style.css file and add these lines:
header {
background-color: #f90;
}
article {
background-color: #fff;
}
footer {
background-color: #b1b1b1;
}
Save the file and open our HTML document in your browser. You will see something like this:
Notice one very important thing - you didn't changed your HTML one bit! That is due to the full separation of concerns I mentioned in the first part.
Image Attributes
Let's see how you can add an image as background to our blog. Extend the CSS file with this code:
h1 {
background-image: url('green.jpg');
}
To add the image with background-image you can plan on how it will be used. With the nice option of background-attachment you can set how the selected tag and the attached background image will move. The default - scroll - value tells the browser to move the tag and it's background together. However, changing that to fixed will give you the effect of the tag as it moves over its background images. Now let's see it.
h1 {
background-image: url('green.jpg');
background-attachment: fixed;
}
Update your CSS file according this sample. Open (or refresh) the HTML page and slowly scroll down the page - see the effect?
Text Attributes
This group of attributes is used to define how text is rendered in the browser. Using them can help make your HTML document much easier to read.
In the last attempt we added a fixed background image to our blog's title. However, that strip of the title looks a bit thick and not too impressive. Now let's change it.
h1 {
background-image: url('green.jpg');
background-attachment: fixed;
line-height: 4em;
}
The line-height sets the height of the line of the text, the 4em value tells the browser to multiply the original height four times (we will talk about CSS units in the next part).
Now our blog looks a bit better.
Now let's see other text formatting options.
Definition
| Explanation
|
letter-spacing
| Used to change the spacing between letters, can be negative too (will stick the letters together)
|
word-spacing
| Used to change the spacing between words, can be negative too (will stick the words together)
|
white-space
| Specifies how white space should be interpreted in text
- normal - continuous white spaces are combined, text will wrap as necessary
- nowrap - continuous white spaces are combined, text never wrap automatically
- pre - white spaces and breaks are preserved just like in the PRE tag
- pre-wrap - white spaces and breaks are preserved, text will wrap when necessary too
|
text-align
| Specifies the horizontal alignment of text inside its container, values are center, left and right
|
text-indent
| Used to change the indentation of the first line of a text, can be negative too
|
text-transform
| Specifies how text case should be changed, values are capitlize, lowercase and uppercase
|
text-decoration
| Specifies how to decorate text, values are overline, underline and line-through
|
And now let's see some action. Update your CSS with this code, save it and open the HTML document.
h1 {
background-image: url("green.jpg");
background-attachment: fixed;
line-height: 4em;
text-transform: uppercase;
}
header > aside {
letter-spacing: +0.15em;
white-space: nowrap;
}
You should see something like this in the header of the page:
As you can see I made my name to spread a bit wider using letter-spacing
(actually added 15% of the original size). The blog title turned to uppercase using text-transformation
. What cannot be seen here is that I prevented any kind of line break on both text using white-space
attribute.
Now add these lines too:
article h2 {
letter-spacing: +0.1em;
word-spacing: +0.1em;
white-space: nowrap;
}
article h3 {
text-decoration: underline;
white-space: nowrap;
}
article p {
text-indent: 1.5em;
}
article p.publish-date {
text-align: right;
}
article aside {
text-decoration: line-through;
}
Let's see what happened. The article title became wider, using word-spacing
and letter-spacing
. The section title got underlined using text-decoration
. The publication date displays on the far right side because of the text-align
attribute. Every paragraph in the article is indented using text-indent
and the side note (marked by ASIDE) got a line over it.
Finally, add this last rule to your CSS file and let's see what it does.
footer p {
text-align: center;
letter-spacing: +0.05em;
}
That last bit set the copyright message to the center, using text-align
and made it a bit wider using letter-spacing
.
Now I want you to take some time to play with these attributes until you able to see how they change the visual presentation of your content. Specifically check the selector groupings I used, to see that you understand them.
Font Attributes
In CSS fonts are selected as family. It means that different styles, like normal, bold and italic of the same font can be selected once. CSS can get font names directly or you may select one of the generic family names defined by CSS. You can set the size of the font (we already saw it with the different headings in our blog) and the styling.
Definition
| Explanation
|
font-family
| Selects the font to use, it can contain a list of font names separated by comma (,), in which case the first font found on the system will be used. If none of the font is found the browser will use the default font declared in it's settings.
Font can be selected also by using one of the generic family names:
- serif - a nice font for of newspaper and book style, like Times New Roman
- sans-serif - simpler than the serif group, lacking all the little strokes of that family, Arial is a sample for that kind of font
- monospace - this family of font has fixed width and mostly used for code representation, Courier is one of the family
- cursive - more artistic fonts, sometimes mimic handwriting, Comic fonts are a nice example
- fantasy - decorative fonts, like Impact
|
font-size
| Set the size of the font to use. Can be a numeric value (like 2em or 4cm or 120%), or one of the predefined keywords: xx-small, x-small, small, medium (default), large, x-large, xx-large or
- smaller - smaller than the inherited size
- larger - larger than the inherited size
|
font-weight
| Sets thickness of the font. Can be a numeric value from the list 100, 200, 300, 400, 500, 600, 700, 800, 900 or the keywords normal (same as 400), bold (same as 700) or
- bolder - thicker than the inherited value
- lighter - thinner than the inherited value
|
font-style
| Can be one of the keyword values - normal, italic or oblique
|
font-variant
| Can be normal or small-caps only. When it set to small-caps all the lowercase letters will turn into a smaller sized uppercase letter.
|
No let see our updated CSS file and how it rendering...
body {
font-family: serif;
font-size: 1.2em;
}
header {
background-color: #f90;
}
article {
background-color: #fff;
}
footer {
background-color: #b1b1b1;
}
h1 {
background-image: url("green.jpg");
background-attachment: fixed;
line-height: 4em;
text-transform: uppercase;
font-family: fantasy;
font-size: 3em;
font-weight: 900;
}
header > aside {
letter-spacing: +0.15em;
white-space: nowrap;
font-family: monospace;
}
article h2, article h3 {
font-family: sans-serif;
font-weight: 700;
font-variant: small-caps;
}
article h2 {
letter-spacing: +0.1em;
word-spacing: +0.1em;
white-space: nowrap;
font-size: 2.5em;
}
article h3 {
text-decoration: underline;
white-space: nowrap;
font-size: 2em;
}
article p {
text-indent: 1.5em;
}
article p.publish-date {
text-align: right;
font-family: monospace;
font-style: oblique;
font-weight: bold;
}
article aside {
text-decoration: line-through;
}
footer p {
text-align: center;
letter-spacing: +0.05em;
font-family: monospace;
}
The blog header.
The article body.
And the bottom line.
I want you now to read the CSS and don't let it go until you understand what it sais...
No Font for Me
Now that we understand all those nice font features let me ask you a question. What if you can't afford to use any substitution of your font? What if the font you used for your site is a must-have (think about site for designers, there the design is everything - it cannot be changed)? Everyting we saw up until now cannot give you a solution, so let me introduce you a new rule - @font-face...
@font-face
is one of the numerous at-rules of CSS (named after the at - @ - sign it begins with). These type of rules do not select a tag using the selectors we know, but instead create a reusable peace of information for the CSS rendering engine. In our case @font-face
is used to create a new font family that we can later use in the font-family
attribute. When using the at-rules you have to put them before every standard selector that uses the information from the at-rule.
Now what is so special about @font-face
? Using it once can load fonts that are not on the client's computer, and by this release designers from the pain of missing local fonts.
Let see the details:
Definition
| Explanation
|
font-family
| Defines the name of the font. It can be used later in the font-family attribute.
|
src
| Defines from where the font should be downloaded, just like in the case of images.
|
font-stretch
| Defines the stretch property of the font. The value can be one of these keywords: normal (default), condensed, ultra-condensed, extra-condensed, semi-condensed, expanded, semi-expanded, extra-expanded, ultra-expanded
|
font-style
| Defines the style property of the font. The value can be one of these keywords: normal (default), italic, oblique
|
font-weight
| Defines boldness property of the font. Can be a numeric value from the list 100, 200, 300, 400, 500, 600, 700, 800, 900 or the keywords normal (same as 400), bold (same as 700)
|
unicode-range
| Defines the range of unicode characters the font supports. Default value is "U+0-10FFFF", means all
|
Let see an example that defines a new font family, NothingYouCouldDo
, based on a font file from Google...
@font-face {
font-family: 'NothingYouCouldDo';
font-style: normal;
font-weight: normal;
src: url(http://themes.googleusercontent.com/static/fonts/nothingyoucoulddo/v4/jpk1K3jbJoyoK0XKaSyQAZsYoLsUhJo8DEpooYVMXYU.woff) ;
}
Now you can use it in our CSS by referencing the family-name
we just declared. So update the header > aside rule to look like this:
header > aside {
letter-spacing: +0.15em;
white-space: nowrap;
font-family: NothingYouCouldDo;
}
My name in the header looks different now and it will look like this whenever you have the font on your system or not!
The WOFF Format
You may have noticed that the src for the @font-face
declaration is pointing to a file with woff extension. It is probably not a format you recognize and that is because it was created for the web exclusively.
To learn about woff format start here: Web Open Font Format.
If you want to create a woff file from one of your fonts for learning purposes, or want to find some ready-made woff files visit this site: Font Squirrel.
Summary
I believe that with this part you really got the feeling how things work around HTML and CSS. You know now how to do some basic (and not so basic) visual formatting on your page, but if you had seen some web sites out-there you can understand that we have a long way to go (hint the next part is about CSS too).