Using CSS to make your web pages pretty

After the previous lesson you should be able to select pretty much anything you want to in any given HTML page. This is really useful, as it is how styles are applied to elements in 95% of web sites (the only exceptions being some JavaScript frameworks).

Do you remember what we said in Part 1 about the separation of concerns? That it's really useful to be able to separate out our content from our styles?

Take a look at the following 2 websites: CSS Zen Garden with nature theme

CSS Zen Garden with nature theme

What do you notice about them?

If you're looking carefully you'll notice that the content is identical, because they are in fact the exact same HTML, just with a different style sheet applied.

The website is called CSS Zen Garden and it is a collection of a lot of different stylesheets that can all be applied to the exact same HTML! Just by changing the stylesheet we can entirely change the website's look and feel.

So now we can select basically any element on our page, what kinds of styles can we apply?

Some common CSS properties

Styling Text

Firstly, let's take a look at the different things we can do with text in CSS. The CSS properties affecting text display can fall into two large categories:

  • Font Styles which are properties that affect the font that is applied to the text, affecting what font is applied, its size and shape and any styling effects (such as bold or italics) that are applied.
  • Text layout styles which are properties that affect the spacing, layout and other features of the text, allowing us to manipulate the space between lines and letters and how the text is aligned.

You should remember that all the text within an element will be affected by any style you apply to that element. To style specific parts of the text in an element (for example just one word, or just one letter) you need to wrap that part of text in HTML such as a <span>.

Fonts

The first thing to remember in HTML is that by default in your websites you can only use Fonts that your user has installed on their machine. That means, if you want to use a nice fancy new font you just found for your CV, your user needs to have that same font installed on their computer already, otherwise they will just see plain text in a default font such as Helvetica, Arial or Times New Roman.

Web safe fonts

Back in the olden days of the web (like... before 2005) web designers were limited to using what we call Web Safe Fonts. These are fonts that we can be sure are installed on pretty much every computer that will be accessing the web. I'm sure you'll recognize most of them:

  • Arial, a sans-serif font, very similar to Helvetica
  • Courier New, a monospace font used to display code (some machines will have Courier instead)
  • Georgia, a serif font
  • Times New Roman, a serif font (some machines have Times instead)
  • Trebuchet MS, a serif font (not widely available on Mobile)
  • Verdana, a sans-serif font

When we write a font declaration in CSS we often provide mutliple fonts, in order of 'preference', so that if one of the desired fonts is not available, the next one in the list is tried. Check out the font-rule below:

font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;

This tells the browser to look first for Helvetica Neue, then Helvetica if it can't find it, if not Arial, and finally if none are available, just to use the default sans-serif font.

It's good practice to make the last font in the font stack a generic type. The following generic types are available:

  • sans-serif
  • serif
  • monospace
  • cursive

If the terms 'Serif' and 'Sans Serif' don't mean anything to you, I thoroughly recommend you check out the website below which has a bunch of really useful information about fonts and typography:

Fonts.com - Serif vs Sans for Text

Web Fonts

Unfortunately, even with these 5 really awesome web fonts, modern web designers weren't happy and wanted more variety in the fonts they could use on the web.

To get around this problem, people used to use images of text in a specific font instead of the font, but this is not practical on a large scale (and besides, Google and other search engines can't read images very well yet).

As such, a new way of using fonts was introduced into CSS, called Web Fonts. When we use a web font, we :

  • Put the font on our server available for the browser to download
  • Link the font file to the Font Name in our CSS
  • Use the Font Name in our CSS to style text. The browser will download and temporarily store the font to display the web page.

Even though we don't directly see it, web fonts are downloaded to the browser when they are used. This means that if you use lots of different lovely web fonts, your page may get quite large and slow to download. As such you should limit your web font choices to things you really really need.

Linking the font looks something like this, we can put this rule at the top of our CSS file:

@font-face {
    font-family: myFirstFont;
    src: url(sansation_light.woff);
}

Now every time we use the font 'myFirstFont', the browser will apply the font found at sansation_light.woff (a file we uploaded onto our server).

Google Fonts

For the purposes of this class we will use Google Fonts.

Google fonts is a cloud-based service, provided for free, that allows us to include a wide variety of fonts easily into our page.

When using Google fonts, google hosts the Font and the CSS that makes it work on their server. All we have to do is get the required font-link, add it to the <head> of our HTML, and start using the font.

Take a look at all the fonts available on Google fonts and choose one.

In Google Fonts copy the <link> tag that will make your font work:

Google Fonts link

Make a new HTML document (with the correct markup) and add some text and a heading.

Now using CSS, style the heading or the paragraph text (or even the whole body) of your page with this font. It's pretty easy.

In my Example I chose 'Open Sans'.

Therefore I include the following link in my ``:

<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">

Now I write the following CSS:

h1, h2, h3, h4, h5, h6 {
  font-family: "Open Sans", Helvetica, Arial, sans-serif;
}

Notice that I included a fall-back font, in case for whatever reason the Open Sans isn't available.

Now try this with any font you link. You can even select multiple fonts in Google Fonts and try with both!

Applying a font face

By now you've probably worked out that the CSS property to change the font of different text is font-family, followed by a comma-separated list of fonts going from the one we want the most, to the fall-back and then the default at the end.

Font properties

In addition to changing the Font itself, we can apply different properties to the font, notably :

  • Change the font weight (bold, normal, light) with: font-weight, which takes the values 100, 200, 300, 400, 500, 600, 700. You can also use bold as a shortcut for 700 and normal as a shortcut for 400.

  • Change the font-size (the size of the text) using font-size which takes a size in any supported CSS unit (in our previous examples we used px for pixels. We'll look at the other units a bit further on in this class).

  • Change the font style (italic or not) with the property font-style which takes either italic or normal (and some other properties but let's not worry about those.

Without trying it out, can you tell what the code below will do?

h1 {
  font-family: Helvetica, Arial, sans-serif;
  font-weight: bold;
  font-style: italic;
  font-size: 30px;
}  

Now try it out in your HTML file.

  • How would I change the text from bold to normal?
  • How would I change the size to 20 pixels?

Color

We also saw in the previous part that we can use the property color to change the color of the text of different elements.

Note that color changes text color whereas background-color will change the color of the background of a block element.

To make the text of all our titles red, we can use the rule :

h1, h2, h3, h4, h5, h6 {
  color:  red;
}

We can use the names of some colors like this in CSS. Check out this table for a full list of color names that CSS supports.

However, these colors only represent 140 of the thousands of colors we can describe in HTML.

Using Hex values to describe colors

Another way of describing colors in CSS and HTML is to use Hex values.

h1, h2, h3, h4, h5, h6 {
  color: #f65a44;
}

This hex value: #F65A44 represents a nice orange-y color.

The Hex code always starts with a # and is always composed of 6 hexadecimal digits. Each pair of 2 digits represents an amount of red, green and blue, and each digit can go from 0->9 and then from A->F. Thus, #FFFFFF is pure white (each color red, green and blue is at 100%), #000000 is pure black, #FF0000 is pure red (Red is 100%, other colors 0% etc.)

You don't need to know too much about how this works, but if you've interested, check out: How Hexadecimal colors work.

Using RGB values to describe colors

We can also use straight RGB values to describe colors in CSS.

h1, h2, h3, h4, h5, h6 {
  color: rgb(246, 90, 68);
}

This is strictly the same as the previous hex color (go ahead, try it!). In this case, we start with the keyword rgb in CSS, and then within the brackets we put the values for red, green and blue respectively.

Using RGBA values to describe colors with transparency.

In the later versions of the CSS3 specification, we can also use rgba notation to describe a color and a degree of transparency (or opacity).

rgba stands for red, green, blue, alpha. Alpha is the channel in Graphic Processing used to describe transparency. An alpha value of 0 is entirely transparent (i.e. invisible), an alpha value of 1 is entirely opaque.

Can you work out what the following rgba code means?

h1, h2, h3, h4, h5, h6 {
  color: rgba(246, 90, 68, 0.7);
}

Other text properties

We can also use properties to describe text alignment, letter and line spacing, line height, and a number of other properties:

  • text-align takes left, center, right and justify.
  • line-height takes a number value (1 = same height as text)
  • text-shadow allows us to apply shadows to our text. Check out the specification here.

Copy the following text:

The best taco bowls are made in Trump Tower Grill. I love Hispanics! He’s not a word hero. He’s a word hero because he was captured. I like text that wasn’t captured. You have so many different things placeholder text has to be able to do, and I don't believe Lorem Ipsum has the stamina. He’s not a word hero. He’s a word hero because he was captured. I like text that wasn’t captured.

When other websites give you text, they’re not sending the best. They’re not sending you, they’re sending words that have lots of problems and they’re bringing those problems with us. They’re bringing mistakes. They’re bringing misspellings. They’re typists… And some, I assume, are good words. You’re disgusting. If Trump Ipsum weren’t my own words, perhaps I’d be dating it.

Some people have an ability to write placeholder text... It's an art you're basically born with. You either have it or you don't. Trump Ipsum is calling for a total and complete shutdown of Muslim text entering your website.

Some people have an ability to write placeholder text... It's an art you're basically born with. You either have it or you don't. Be careful, or I will spill the beans on your placeholder text.

Apply HTML paragraphs and give your text a heading.

Try out different text-align values, different line-heights, and different text-shadows to see the effect it has.

Styling blocks

Let us leave text alone for a moment: by now you can probably do most basic text styles, and you're probably wondering how we get from here to the crazy layouts available on CSS Zen Garden.

One of the most important parts of CSS when designing a web page is box styling.

Box styling basically has 5 main parts:

  • Backgrounds
  • Box size
  • Padding
  • Margins
  • Borders

Backgrounds

Copy the following code to an HTML file and open it in your browser:

<nav class="navigation"><a href="/html/">HTML</a> |
  <a href="/css/">CSS</a> |
  <a href="/js/">JavaScript</a> |
  <a href="/jquery/">jQuery</a>
</nav>

Now apply the following CSS (either in the head or in an external style sheet, your choice).

.navigation {
  background-color: #e0e0e0; 
}

Notice that the nav box now gets a nice gray background.

We can change the background-color of elements using background-color.

We can also use background-image: url('/images/myimage.png') to add backgrounds, and we can use the properties background-repeat, background-position and background-size to modify the repeat, position and size of the background images.

If you want to learn more about backgrounds, you can complete the following tutorial which covers the basics:

Background Image tutorial

Box size

We can set the height and width of a block element in CSS using the height and width properties.

.navigation {
  background-color:  #e0e0e0; /* just so we can see the box */
  height: 100px;
  width:  150px;
}

Try this code out. What happens?

How about if you use a % instead of px ?

height and width will try and set the height and width of our box, but sometimes the content inside the box is too big to fit. In this case we will see the text overflow outside the element.

Try setting a really small height and width and see what happens.

We can stop this happening by setting overflow: hidden; on the box.

Try this now.

We can also set dynamic height and width (the defaults in fact) by using height: auto; or width: auto;. In this case the box will take up 100% of the screen width (by default) and the height will adjust to the content.

Finally, we can also use min-height and max-height, and the same for width, in order to define a minimum and maximum height. This have priority over height and width so if an element has min-height: 100px; height: 80px; it will still be rendered 100px high.

Padding, Margin and Border

Perhaps the easiest of these three to understand first of all is border. Border defines... you guessed it... a border around an element !

Try out the following CSS : ```css .navigation { border-width: 1px; border-color: black; border-style: solid; } ``` Do you see the border around your navigation element? Other border styles are `dotted`, `dashed`. You can try these out.

Instead of writing out :

.navigation {
  border-width: 1px;
  border-color: black;
  border-style: solid;
}  

We can just write :

.navigation {
  border: 1px solid black;
}

These are called short-hand properties, and they allow us to be more efficient when writing CSS. You must provide the required parameters in the right order.

Remember all those background properties we saw before? We could also use a shorthand property:

body {
  background: url('/images/cat.png') no-repeat top center;
}
Padding

Now we've seen 'border' let's take a look at padding.

Leave the border active for the moment.

padding is a very common property. It adds spacing between the border of an element and its content.

.navigation {
  border: 1px solid black;
  padding-top: 10px;
  padding-right: 10px;
  padding-bottom: 10px;
  padding-left: 10px;
}

What does this do to your element?

You should notice more spacing between the content of the element, and it's border.

There is also a shorthand property for padding:

padding: 10px;

This will apply 10px padding to all sides of the element.

padding: 5px 10px 20px 10px;

This will apply top padding of 5px, right padding of 10px, bottom padding of 20px and left padding of 10px.

The order is important, as the padding property expects the paddings to come in this order (that is, in the order of compass points, N E S W).

Margin

Now we've seen padding, let's try out Margin.

Where padding adds spacing inside the element, margin adds spacing outside the element.

Try the following:

.navigation {
  border: 1px solid black;
  margin-top: 10px;
  margin-right: 10px;
  margin-bottom: 10px;
  margin-left: 10px;
}

What effect does this have?

Using your HTML have a look and see what happens when:

  • You use a negative number for the left padding.
  • You use a negative number for the top padding.
  • You use percentages for the padding instead of pixels
  • You set 'margin-left' and 'margin-right' to auto.

Positioning elements

Now we've gotten styling and sizing our blocks down, let's think about how we position them in the page.

By default a web page is made of blocks that simply run from top to bottom:

Foundation example top to bottom

But we can use a few techniques to make all sorts of interesting page layouts:

Layout examples

These layouts are called design patterns.

Floats

One of the most basic ways of getting content to go to the left or the right of the page, is to use the property float.

CSS floats are a bit complicated to understand. The best way to demonstrate it is to copy the code below and open it.

<p>The best taco bowls are made in Trump Tower Grill. I love Hispanics! He’s not a word hero. He’s a word hero because he was captured. I like text that wasn’t captured. You have so many different things placeholder text has to be able to do, and I don't believe Lorem Ipsum has the stamina. He’s not a word hero. He’s a word hero because he was captured. I like text that wasn’t captured.</p>

<div class="block">
This is a block
</div>

<p>When other websites give you text, they’re not sending the best. They’re not sending you, they’re sending words that have lots of problems and they’re bringing those problems with us. They’re bringing mistakes. They’re bringing misspellings. They’re typists… And some, I assume, are good words. You’re disgusting. If Trump Ipsum weren’t my own words, perhaps I’d be dating it.</p>

<p>Some people have an ability to write placeholder text... It's an art you're basically born with. You either have it or you don't. Trump Ipsum is calling for a total and complete shutdown of Muslim text entering your website.</p>

<p>Some people have an ability to write placeholder text... It's an art you're basically born with. You either have it or you don't. Be careful, or I will spill the beans on your placeholder text.</p>

And this CSS :


.block {
  width: 200px;
  height: 100px;
  background-color: gray;
}

Now take a look at the output.

Now apply the following CSS to the block. What happens? float: left;

What about if we do float: right;?

Now remove the float property, and duplicate the block so your code looks like this:

<p>The best taco bowls are made in Trump Tower Grill. I love Hispanics! He’s not a word hero. He’s a word hero because he was captured. I like text that wasn’t captured. You have so many different things placeholder text has to be able to do, and I don't believe Lorem Ipsum has the stamina. He’s not a word hero. He’s a word hero because he was captured. I like text that wasn’t captured.</p>

<div class="block">
This is a block
</div>

<div class="block">
This is a second block
</div>

<p>When other websites give you text, they’re not sending the best. They’re not sending you, they’re sending words that have lots of problems and they’re bringing those problems with us. They’re bringing mistakes. They’re bringing misspellings. They’re typists… And some, I assume, are good words. You’re disgusting. If Trump Ipsum weren’t my own words, perhaps I’d be dating it.</p>

<p>Some people have an ability to write placeholder text... It's an art you're basically born with. You either have it or you don't. Trump Ipsum is calling for a total and complete shutdown of Muslim text entering your website.</p>

<p>Some people have an ability to write placeholder text... It's an art you're basically born with. You either have it or you don't. Be careful, or I will spill the beans on your placeholder text.</p>

Update your CSS to this:

.block {
  margin: 10px;
  width: 100px;
  height: 50px;
  background-color: gray;
}

Now apply float: left to the 'block' class. What happens to the blocks?

What about if you apply float: right ?

Using floats is one of the most basic ways to move content around on the page and position it where we want.

To produce a complicated layout we might need to create a lot of divs and use a lot of floats to achieve the result we want.

The position attribute

Whereas floats can move elements around in the flow of the page (pushing them left and right) we can also move elements using the position attribute.

Understanding position is a bit tricky, but the basic principles are this :

  1. All block elements are, by default, set to position: static. This means they are in the flow of the rest of the elements of the page (ie. if you add things before them or around them, they move around and flow to accommodate them).
  2. The position property has 3 other possible values: absolute, relative and fixed.
  3. In any of these other states, you can use the position properties top, left, bottom, and right on the object.
  4. When the position is relative, the object will move relative to where it would normally have been in the page.
  5. When the position is absolute, the object moves based upon its nearest parent with position not set to static. It is removed from the flow of the page, so other elements behave like it doesn't exist.
  6. When the position is fixed, the object is positioned relative to the browesr window (ie. it doesn't follow the page when we scroll like elements usually do). It is removed from the flow of the page.

The best way to understand this, is to try it out for yourself. Take our previous Trump Ipsum HTML from above (the one with just 1 block), and modify the CSS :

.block {
  top: 15px;
  left: 15px;
}

Now add position: relative and refresh. What has happened? Do you see how the page still behaves as though the element was in its original place, but the element has visually moved down (from the top) and right (from the left) by 15px each?

Now change it to position: absolute and refresh. What happened? The element now is completely removed from the flow of the page, and has positioned itself 15px away from the top and left of the body element (aka the page).

Now switch to position: fixed and resize your window so you have to scroll a bit. What happens?

Check out the video below for a quick demo of using the position attribute and how it affects the display of block elements.

Display

The last really important property we will look at is display.

Block vs inline

As we saw before, all HTML elements are by default either block elements like div or inline elements like span.

The display property in CSS allows us to cheat a bit, and transform one type of element into the other.

Take the following example

The best taco bowls are made in Trump Tower Grill. I love Hispanics! He’s not a word hero. He’s a word hero because he was captured. I like text that wasn’t captured. <a href="#" class="link">You have so many different things</a> placeholder text has to be able to do, and I don't believe Lorem Ipsum has the stamina. He’s not a word hero. He’s a word hero because he was captured. I like text that wasn’t captured.

Take a look in the browser. Nothing out of the ordinary, the a is behaving like an inline element.

Now add the following css :

.link {
  display: block;
}

Refresh the page. What happened?

Using this method we can force normally inline elements like a to become blocks, and vice versa.

This can be useful because as we saw before, we're not supposed to put block elements inside inline elements. Now we can switch their type so that we can!

Display: none

Try putting the link to display: none;. What happens?

Yep! Exactly, the page behaves like that element completely doesn't exist.

Display: inline-block;

Take the following markup for a navigation bar:

<nav>
  <div class="link-holder"><a href="#">Link 1</a></div>
  <div class="link-holder"><a href="#">Link 2</a></div>
  <div class="link-holder"><a href="#">Link 3</a></div>
  <div class="link-holder"><a href="#">Link 4</a></div>
  <div class="link-holder"><a href="#">Link 5</a></div>
</nav>

Use this CSS to see better what is happening:

.link-holder {
  background-color: gray;
  margin: 10px;
}

Check it out in the browser.

Now try adding display: inline-block, and width: 100px. What happens?

Indeed, inline-block is kind of a hybrid display mode. It arranges the elements as though they were inline, but allows them to have backgrounds, height and width and all the properties we expect from blocks.

This can be useful for creating horizontal menus and such, without resorting to using flex-box or floats.

Units

The last thing we're going to cover in our basic class is units.

We've already seen some units in CSS:

  • px which is equivalent to pixels
  • % which is equivalent to percentage of the parent element

But let's add a few more one's you'll probably see:

  • em
  • rem

em

em is a funny element. It is equivalent to the size of the current font-size at the place where it is used.

So if we have in the body of our document a paragraph and we set the size to 1.2em, our text will be 1.2x the size of the body font-size.

If we do the same thing on an h1 though, it will be 1.5x the size of the h1 font size.

This can be useful when we're designing buttons for example, where we want the padding and margins to be proportional to the overall size of the button. If we design the whole button using em, we can just increase the font size and all the dimensions of the button will increase.

<a href="#" class="button">Button!</a>
.button {
  display: inline-block;
  padding: 0.5em 1.5em;
  background-color: gray;
}

Try increasing the font-size of the button with CSS. What happens to the padding?

rem

rem stands for relative em. A relative EM is basically the em unit, but without all of the funky 'changing-with-the-current-font-size' functionality. It basically is like em but it is always relative to the body font-size. So wherever you use it, 1rem is 1x the current body font-size.

Wrap up

Now you should have a bit of any idea of how CSS works and what you can use it for.

The best way to learn the next parts is simply to practice by trying out some exercises. There are a few exercises below which should go back over the basics we learned here, and then stretch you to learn some more CSS and some new properties.

Exercises

Ungraded Exercise : Exercise 2

This is an ungraded exercise for practice only, you don't need to submit it for grading

Copy the given HTML into a new document and submit it like last time.

  1. Do exercises 1-5 from the w3 schools font section

Ungraded Exercise : Exercise 3

This is an ungraded exercise for practice only, you don't need to submit it for grading

Take your CV markup from Lesson 1.

  1. Apply a different font for the headings (use a Google font)

  2. Apply a different font for the body text.

  3. Change the color of the headings

  4. Add a border to your photo and your contact information. The border color should be a Hex color.

  5. Use the paddings and margin to make the spacing on your CV more interesting.

Ungraded Exercise : Exercise 4

This is an ungraded exercise for practice only, you don't need to submit it for grading

  1. Use the tutorial linked to create a 2 column layout :

2 column layout tutorial

  1. Now apply the same principles to make the below layout (3 equal width columns of content, a header and a footer).

3 column layout

Graded Exercise : Exercise 5

This is a GRADED EXERCISE. It is for practice, if you submit it you will get a grade and a comment. These DO NOT count towards your grade for this class

Take the mini website you made in Lesson 1.

  1. Use CSS to lay out the navigation menu as 4 buttons from left to right (in a horizontal line). The buttons should be square, have a background color, and should go from left to right in the correct order.

  2. Apply the layout you made in exercise 4 to your website. Give your website some nice background-colors, link colors, fonts and use padding and margin to lay it out nicely.

Be as creative as you wish with this part.

Extension

If you're really interested in CSS and want to learn more, here are some interesting resources focusing on some interesting areas of CSS.

Positioning:

http://learn.shayhowe.com/advanced-html-css/detailed-css-positioning/

Flexbox

http://learnlayout.com/flexbox.html

Using a Framework

it is becoming more and more common to use a framework to write your CSS. Check out the following tutorial and also download and try out a framework like 'Bootstrap' or 'Foundation'

Getting started with Bootstrap Getting started with Foundation

The cascade

The cascade is one of the really important parts of CSS. Understanding it properly is fundamental if you want to master CSS.

Understanding the cascade

Mozilla: Cascade and Inheritance