CSS is the acronym for 'Cascading Style Sheets'.
CSS is an extension of HTML that is used to specify how webpage elements should be styled and positioned.
Before CSS was introduced, web designers had to add styling attributes to every instance of an element that they wanted to style differently from the browser defaults.
Also, the positioning of content on the page in a non-linear fashion would require a number of workaround techniques (hacks) often using elements inappropriate for the content, leaving a messy document structure and potential accessibility issues.
These sets of rules can also be specified for different output types. For example, you might decide that all links will be presented as normal text when printed since they are not clickable after being printed and that any background colours can be removed to save toner/ink and improve readability.
Advantages of using CSS
- Can save time and effort when applying styling to content, especially for large websites.
- Saves even more time and effort if changes need to be made. A simple change to the style sheet can instantly update the styling of every webpage throughout a website. Imagine if you were managing a website with thousands of articles and it was decided that a new corporate colour should be used for each of the headings. If the colour information had been individually applied to each heading, it might take a long time to update the entire site, but with CSS it would take seconds to make this massive change.
- Styling code does not need to be replicated; this reduces document sizes, therefore reducing the data usage and time required to send webpage data over the internet.
- Presentation is separate from the content, allowing for the content to be easily repurposed or displayed differently on different devices.
- Styles let you control the text in ways that are out of reach of HTML tags, such as line spacing (leading), colour, font styles—among many other properties.
Disadvantage of using CSS
- Applying formatting remotely from the content can be a difficult concept to get used to and may seem to over-complicate the process, especially when creating simple pages.
Marking up the page content with HTML elements
The primary way for CSS to target content for styling is by targeting the element applied to the content.
The default browser styling for any element can be modified or completely overridden by CSS. It is important that you have marked up your content thoroughly with semantic elements.
Remember to structure your content using appropriate sectioning tags; e.g. <nav>
, <section>
, <aside>
, etc.
As a last resort, apply <div>
and <span>
elements to any content that cannot be targeted by a semantic element.
CSS will typically target elements globally, meaning every element that matches a CSS selector will have the same styling rules applied.
Sometimes you will want to exclusively target a specific instance of an element, or a group of elements’ instances containing content that needs to be styled separately. To do this, you can name elements using an 'id' or a 'class' attribute. <div>
and <span>
elements will typically require naming.
Applying id attributes
An id will specify a unique name for an instance of an element. No other element can share the same id. It can be added to most elements’ Start tags. Add a #
to an element such as a <p>; e.g.
: #para1 { color: red; text-align: center; }
Here is the next simple application of CSS style using id attributes on 3 different <p>
paragraph tags:
Note: It is best to use lowercase letters and numbers with no spaces or punctuation when providing id and class name values.
Applying classes
A 'class' is much like an id, except the same class label can be applied to multiple items to form a group of items that can be formatted identically.
You could solely use class attributes in place of id attributes; however, an id does have advantages over a class, such as automatically becoming an anchor for linking to and they can be easily accessed by JavaScript.
An item can have both a class and individual id applied if necessary; e.g. we use class="center"
for <h1>
and <p>
:
The example below "The anatomy of CSS" shows the correct syntax for an element in an external or embedded style sheet.
- Selector
- Declaration
- Declaration
- Property
- Value
- Property
- Value
A 'CSS rule' consists of:
- a
selector
that specifies what content will be targeted - followed by one or more
declarations
that define how the content will be styled or positioned - declarations are enclosed in curly brackets
{}.
Defining selectors
There are a few ways of defining a selector or selectors:
- A specific element in the style is to be applied to; e.g. all
<p>
or paragraph elements style are targeted:p { declaration; }
- An id is specified using a hash
#
symbol immediately before the name:#id { declaration; }
Note: An id name cannot start with a number. - A class is specified using a period
.
symbol immediately before the name:.class { declaration; }
- Specific elements belonging to a class or id can be targeted by the following syntax:
h1.news { declaration; } div#top-story { declaration; }
These are the basic selectors that you will be using most often.
Grouping selectors
To minimise the code, it is better to 'group' elements with the same style definitions. To group selectors, separate each selector with a comma. This example will show headings 2, 3, and 4 in bolded, orange type.
h2, h3, h4 { color: orange; font-weight: bold; }
Defining a declaration
In the previous examples, we have seen that every selector is to be accompanied by a declaration.
So, what does a 'declaration' consists of?
A CSS declaration consists of a property
followed by a value
—separated by a colon :
and ending with a semicolon ;
property: value;
If the property you have chosen is color
, then you need to define what value
is the color going to be:
property: value;
color: green;
Technically speaking, you don’t need to end a declaration with a semicolon ;
if the rule only contains one declaration.
However, it is a good habit to always add one because if you forget it, your rule will break if you add any additional declarations.
The semicolon in this case, ends the value statement or it can also separate multiple declarations in a rule:
p {color: green; font-size: 12px; font-weight: bold;}
This guide combines declarations on a single line (as shown above) but for extra clarity, individual declarations are often written on separate lines:
h2, h3, h4 { color: orange; font-weight: bold; }
Note: There is no space between the property value and the unit.
Let’s look at how a CSS style sheet can be applied to our basic scones recipe page.
Note how all the contents of our <p>
or paragraph tags have now become orange and in bold. Take note of the other elements that have been styled by the CSS.
Applying styles
CSS stylesheets can be applied as an:
- inline CSS style(s)
- internal or embedded CSS
- external CSS document.
Applying inline styles
Inline styles can be added directly inside elements by adding the style=""
attribute.
They do not require selectors or curly brackets:
<h1 style="text-align: center; color: red;">
Advantages: Useful for quick, one-off formatting requirements and can override other CSS styles.
Disadvantages: Styling is not separated from content. Can be messy and time-consuming to edit.
Applying embedded styles
An embedded stylesheet is usually placed within the <head>
element of a webpage, for example:
<head> <meta charset="utf-8"> <title>Embedded style</title> <style type="text/css"> h1 { color: red; text-align: center; } p { font-style: italic; } </style> </head>
Notice the addition of <style type="text/css">
and the “My Recipe” heading is now in the center [note the US/coding spelling] and in red, following the selector { declaration; }
h1 { color: red; text-align: center; }
And all the <p>
tags are now in italics, following the declaration,
p { font-style: italic; }
Advantages: Keeps the CSS handy within the HTML document but separate from the content.
Disadvantages: Styles cannot be shared with other documents.
Applying external styles
External style sheets are created as separate plain text files and are referenced using the <link>
relationship tag. It also enables you to change the look of an entire website by changing just one file!
Each page must include a reference to the external style sheet file inside the <link>
element. The <link>
element goes inside the <head>
section, replace the my-style.css with your filename.
<head> <link href="my-style.css" rel="stylesheet" type="text/css"> </head>
Advantages: Global (or site-wide) changes are possible. Alternative style sheets can be created for different media (e.g. print, handheld).
Disadvantages: Can be a little disorientating and be an extra hassle if used for very simple webpages.
Multiple style sheets
If some properties have been defined for the same selector (element) in different style sheets, the value from the last-read style sheet will be used.
The order of style sheets matters
If you have an external style sheet for the <h1>
element that defines the following:
h1 { color: purple; }
and an internal style sheet that defines the following:
h1 { color: green; }
After the link
If the internal style is defined after the <link>
to the external style sheet, the <h1>
elements will be 'green'.
Before the link
However, if the internal style is defined before the <link>
to the external style sheet, the <h1>
elements will be 'purple'.
An inline style has the highest priority.
It will override a style defined:
- inside the
<head>
tag - in an external style sheet
- in a browser default value.
Applying alternative style sheets
These days, webpages are accessed on mobile devices first, followed by computer screens.
You can offer multiple variations of style sheets for the same webpage that are optimised for specific devices.
On handheld devices, provide a layout that makes reading and navigation on mobile devices easy.
According to the Mozilla Developer site, there are 3 specific types of output that you can choose to support:
all
(suitable for all devices)print
(intended for paged material and documents viewed on a screen in Print Preview mode)screen
(intended primarily for screens).
To offer any of these options, you must create separate style sheet files and links to them that include the media=""
attribute. For example:
<link href="css/screen-styles.css" media="screen" rel="stylesheet" type="text/css"> <link href="css/handheld-styles.css" media="handheld" rel="stylesheet" type="text/css">
As addressed earlier in this module, the 'C' in CSS is for Cascading.
This refers to the cascade principle used by browsers to determine which style to apply to an element when there is more than one styling rule that could be applied. The cascade takes into account 3 main factors: inheritance, location and specificity.
Inheritance
An element will inherit (take on) many of the style properties that are applied to a parent or ancestor element. For example, consider the following CSS rule applied to the <body>
element:
body { color: red; }
The colour [remember the US spelling 'color' is used in coding] property will also be passed down to all other elements in the document (since all page content is nested within the <body>
element) unless another style rule overrides this inherited property.
Location
As you’ve seen by now, CSS rules can be written in a combination of different locations. If there are conflicting styles in different locations, an inline style will win (overriding embedded and external styles), followed by an embedded style (overriding any external styles).
Specificity
'Specificity' refers to how specifically a rule has been defined.
The rule with the highest specificity wins even if the other rule is located in a winning location.
There is a technical calculation to determine complex conflicts, but essentially you just need to keep in mind the following order:
- an inline style is most specific as it is directly applied to the element
- an
#id
in the rule offers the next highest level - followed by a
.class
(or pseudo-class selector) - and finally an element (or pseudo-element).
Multiple elements or classes used in a selector can also increase specificity (e.g. article p
will override p
).
Box model
All HTML elements may be considered as boxes within boxes.
The CSS box model is essentially a box that wraps around every HTML element. It consists of margins, borders, padding and the content itself:
Float
The float
property is used for positioning and formatting content; e.g. to let an image float left to the text in a container.
The float
property can have one of the following values:
left
- the element floats to the left of its containerright
- the element floats to the right of its containernone
- the element does not float (will be displayed just where it occurs in the text). This is the default.
The float
property can be used to wrap text around images.
Clear
The clear
property specifies:
- what elements can float beside the cleared element
- and on which side.
The clear
property can have one of the following values:
none
- allows floating elements on both sides. This is the default.left
- no floating elements allowed on the left sideright
- no floating elements allowed on the right sideboth
- no floating elements allowed on either the left or the right sides.
The most common way to use the clear
property is after you have used a float
property on an element.
When clearing floats, you should match the clear to the float; i.e. if an element is floated to the left, then you should clear to the left. Your floated element will continue to float, but the cleared element will appear below it on the webpage.
You can use 'comments' to explain your code–this can help when you edit the code in the future. As with HTML comments, CSS comments do not display in browsers.
CSS comments start with /*
and end with */
and can span multiple lines.
/* This is a comment and will not be displayed by the browser. */
Width and height
By default, the content of an element will simply flow across the full width of the browser’s window and its height will vary depending on how much content there is.
So you initially have little control over the layout of a page.
Fortunately, CSS makes it easy for you to specify the width and height of each element.
Use the width property with either:
- a size value (including units)
- a percentage value (a percentage of the parent element’s width—if the element is not nested within another element that has a width specified, this will be a percentage of the browser window width).
Use the height property with:
- a size value (including units)—percentage values are not supported, so:
article { height: 400px; width: 20%; }
By default, the auto value is applied to the width and height if it is not specified.
Specifying minimum and maximum sizes
CSS can be used to restrict the auto-sizing to minimum and maximum width and height values.
Use the following properties (with size values):
min-width
max-width
min-height
max-height
For example:
img { max-width: 768px; }
Responsive image example
Setting the Viewport
<!-- The meta tag --> <meta content="width=device-width, initial-scale=1.0" name="viewport">
The meta tag above can be added to all of your webpages to make them adjust to a client's screen. Your page will then be capable of being responsive once this tag has been added.
Note: Take a moment now to copy the above code for future reference.
Using the width property
Using CSS, you can set the img element's max-width property to 100 per cent, the image will then respond to the element's parent container.
Note: Take a moment now to copy the code below for future use.
img { height: auto; max-width: 100%; }
The color
property can be used to set the foreground colour used by elements (e.g. to colour text).
In addition, you’ll see the same colour values used for this property in many other properties, such as background-color
.
Note: The US spelling of color is essential in the coding.
There are several ways to specify colour:
- using a predefined colour name:
color: teal;
- using a hexadecimal value:
color: #008080;
- specifying RGB (Red, Green and Blue) values or percentages:
color: rgb(0, 128, 128); color: rgb(0%, 50%, 50%);
- specifying HSL (Hue, Saturation and Lightness) values (using degrees 0-360 and percentages):
color: hsl(0, 25%, 100%);
Hexadecimal, RGB and HSL values can often be found in colour pickers of graphics programs or charts can be found online. The following are the basic predefined colours that you can specify in HTML. (They are not case-sensitive.)
There are 130 additional colours. Visit MDN Web Docs for the full list.
You’ll find colour pickers in graphics applications, as well as online tools like workwithcolor.com or coolors.co, to help with colour values.
Translucent colours
Translucent colours can be specified using an alpha value between 0
(transparent) and 1
(opaque) using rgba()
or hsla()
colour values; e.g.:
color: rgba(0%, 50%, 50%, 0.25); color: rgba(0, 128, 128, 0.5); color: hsla(180, 25%, 100%, 0.75);
Opacity
The opacity property lets you adjust the overall translucency of an entire element (including any backgrounds, borders and content).
If you just want to target a specific part of an element, then you should colour that element using an rgba()
or hsla()
colour value.
Opacity is set using a value between 0
(transparent) and 1
(opaque), such as:
article#ghost-story { opacity: 0.75; }
If you apply a background colour to an element containing text, you will notice that the text runs flush to the edge of the element’s container. Often, you will want to add a bit of extra space (a margin) around the text so that the text sits more ‘comfortably’ inside the bounds of the element’s container.
This is known as 'padding'.
Use the padding property followed by:
- a single value (for equal padding all around); e.g.:
p { padding: 24px; }
- 2 values (
top
/bottom
andleft
/right
) - 4 individual values (for
top
,right
,bottom
, andleft
padding in clockwise); e.g.:p { padding: 24px 40px 40px 24px; }
Note: Percentages of the parent element can also be used.
The element on the left has no padding applied and the text looks ‘cramped’.
The element on the right has unequal padding (24px 40px 40px 24px
) as indicated by the values.
Margins add transparent space between the outside of an element and surrounding elements or the edges of the browser.
Use the margin
property followed by:
- a single value (for equal margins all around), for example:
p { margin: 24px; }
- 2 values (
top
/bottom
andleft
/right
). - 4 individual values (for
top
,right
,bottom
andleft
margins in clockwise), for example:p { margin: 24px 24px 40px 24px;; }
Alternatively, margin-top
, margin-right
, margin-bottom
, or margin-left
properties can be used with a single value or percentage.
Note: Percentages of the parent element can also be used.
Centring elements using auto margins
If you have an element that is a fixed width, you can centre it in the browser window or the containing <div>
element by specifying auto margin sizes for the left and right values.
For example:
div#quote { width: 200px; margin: 24px auto; }
The elements on the top row merge together as no margins are specified.
The bottom elements are separated by margins. Note that an automatic margin has been made between the top elements and the browser edge. This is a default in many browsers and can be removed by specifying margin: 0
on the <body>
element.
Borders of many different styles, colours and widths can be applied to an element.
Border width
To specify the thickness, use the border-width
property followed by a size value. For example:
p { border-width: 2px; }
Border color
To specify the border color, use the border-color
property followed by a colour value. For example:
p { border-color: red; }
Border style
Use the border-style
property with one of the following style values:
solid
dotted
groove
inset
outset
ridge
dashed
double
For example:
p { border-style: double; }
Combining border properties
To save time and extra code, you can combine all of the values from each of the properties covered above using the border property. For example:
p { border: 2px red double; }
Note: You can also use border-top
, border-right
, border-bottom
, and border-left
properties to specify different values for different sides of the element.
Using single-sided borders to create dividing lines
Being able to apply borders to only one side of an element is useful for creating dividing lines. For example, applying a thin left border to <div>
container elements that are positioned horizontally will create column rules.
Single borders are also an alternative way of creating horizontal rules.
Using images for borders
The CSS3 border-image
property lets you create customised borders by using an image.
The image must be designed so that it can be divided easily into 9 slices. The 4 corner slices are used in the corners of the border and the outer middle slices will be repeated along the top, bottom, left and right sides of the border.
You are required to use special vendor-specific properties for now. Fortunately, there is an interactive tool that you can use to preview and generate the required CSS.
Applying colours or images to backgrounds can not only be used to enhance pages, but they can also be useful to help you clearly see how structural elements are working when you are learning to apply CSS for sizing and positioning content.
Individual backgrounds can be applied to the entire page (by specifying the body element) and/or to individual elements on the page. Elements that do not have a background specified will be transparent and any underlying backgrounds will show through.
Background colour
Use the background-color
property followed by a color
value (you can use any of the colour value types covered previously). Here are some examples:
body { background-color: aqua; } #main { background-color: #0ff; }
An image can be used instead of, or in addition to, a colour. Use the background-image
property with a value of url()
with the file name and location of the image inserted between the brackets. For example:
body { background-image: url("background.gif"); }
Repeating a background image
A background-image
with a large file size can slow the loading of a web page, so it is common to use smaller images that can be downloaded quickly and repeated (tiled) to fill a larger area.
A repeated image does not need to be a square tile—interesting effects can be created using thin horizontal slivers of an image.
Use the background-repeat property with either:
repeat
(to repeat the image both horizontally and vertically—most browsers use this by default if nothing is specified)repeat-x
(horizontally only)repeat-y
(vertically only)no-repeat
For example:
body { background-image: url("background.gif"); background-repeat: repeat-y; }
Background position
By default, a background image will be placed in the top left corner (and repeated).
You can offset the initial location using the background-position
property and specifying the distance from the left and top using pixel measurements or percentages (of the area).
Alternatively, the following values can be specified: left
, center
, or right
(for the horizontal) and top
, center
or bottom
(for the vertical).
For example:
body { background-image: url("background.gif"); background-position: 20px top; }
In this example, the starting point of the background image will be 20px
from the left and aligned to the element’s top edge.
Background size
The background-size
property can be used to set the size of a background image.
Ideally, as with any image, you should use an image editor for optimised size and quality.
However, if you are creating a 'flexible layout' (to be addressed later), it can be a cool effect to see the background scale along with the elements. These properties have good native browser support for 2 keyword values:
background-size: cover;
cover
- scales in proportion to fit the entire element area, but may clip a portion of the image.
background-size: contain;
contain
- fits the whole image, but may not fill the entire element.
Combining background properties
To save time and extra coding, you can combine all of the values from each of the background properties just described using the background
property. For example:
article { background: #f0f url("background.gif") no-repeat center top; }
Note: Values are separated by a space only and can be in any order.
Adding multiple backgrounds
You can add multiple backgrounds by separating property values for each background property using a comma (,
).
Multiple backgrounds are very useful when you want to overlay background images that have transparency (without it, the backgrounds would just cover others).
They can also be effective when you want to position multiple smaller background images around different sides of the element and leave the middle area plain—this reduces the overall file size of the background and allows for flexible layout. For example:
article { background: url("background-1.gif") left top repeat, url("background-2.jpg") left top no-repeat, url("background-3.png") right bottom no-repeat; }
This could also be written as separate properties, such as in this example:
article { background-image: url("background-1.gif"), url("background-2.jpg"), url("background-3.png"); background-position: left top, left top, right bottom; background-repeat: repeat, no-repeat, no-repeat; }
Note: The first background will be layered at the bottom and any extra backgrounds will be layered on top. Take care to maintain the same value order for each property.
Background gradient fills
Gradient fills use a gradation of colours to fill the background.
.simple-gradient { background: linear-gradient(darkgreen, lightgreen); }
Using the Ultimate CSS Gradient Generator
Fortunately, Colorzilla offers a fantastic interactive tool that will automatically generate for you all of the bloated CSS code currently required to implement gradients with cross-browser support. All you need to do is pick a preset, customise it using the controls and then copy and paste the CSS that is automatically generated.
Box shadows
The box-shadow
property will add a drop shadow effect to an element’s box. This effect will instantly add some depth to a flat webpage.
Note: Text shadows are covered in the next topic.
Use the following syntax:
box-shadow: 5px 5px 15px 2px #444;
5px
- Horizontal offset
5px
- Vertical offset
15px
- Blur radius
2px
- Spread distance
#444
- Color
Note: You can also add the inset value at the start if you want to reverse the effect. Further, you can add multiple shadows by separating the groups of values by a comma (,
). This can help create glowing effects, embosses etc.
Rounded corners
The border-radius
property lets you add rounded corners to an element.
Note: Despite its name, you do not need to apply a border to use this property.
To apply equal radius values to each corner, use:
border-radius: 45px;
To apply different values to each corner to create interesting effects, use:
border-radius: 45px 0px 90px 0px;
Note: The order of the values is: top-left
, top-right
, bottom-right
, bottom-left
.
You can also use the following properties to target individual corners:
border-top-left-radius
border-top-right-radius
border-bottom-right-radius
border-bottom-left-radius
Elliptical corners can be specified by using a forward slash (/
) to separate horizontal and vertical radius values; e.g.:
border-radius: 45px / 90px;
Display and visibility
There are properties and values that affect how an element appears on a page:
display: none;
Will hide the element and collapse the space that the element occupied. This is useful for creating expanding/collapsing menus with JavaScript.display: inline;
Will display the element inline (without starting a new line). For example: if applied to<div>
elements, they can be displayed side by side without using float. Horizontal lists are also possible using inline.display: block;
Will display the element block-level (starting on a new line). For example: if applied to<img>
elements, images will be cleared of text to the left and right.display: hidden;
Is useful for hiding an element without collapsing the space around it.display: visible;
Will make the element visible again.
CSS font formatting properties
Applying 'web-safe' fonts
You can instantly enhance the look of a webpage by specifying fonts (different from the boring browser defaults) to use for the various text-based elements in your website.
But before you get stuck in and start trying out all the different fonts you have installed on your computer, you must first be aware that visitors to your site will not be able to display a font if it is not also installed in their system (unless it has been made available for the browser to download).
So, first, we’ll look at how to limit your choice of fonts to those that are standard on most systems.
Use the font-family
property followed by the name of the font.
If the font’s name contains more than one word then you must enclose it in quote marks; for example:
h1 { font-family: "Arial Black"; }
As font names are not always identical between different operating systems, it is best to provide alternative fonts that can be used.
For example, the Mac OS font Palatino
is called "Palatino Linotype"
in Windows. On systems that do not have this font at all, you can also specify the type of generic font equivalent to use (e.g. serif
).
p { font-family: Palatino, "Palatino Linotype", serif; }
The table below displays 'web-safe' fonts. If you want to use one of these fonts, specify all of the font names across the same row in the table.
Windows font | Mac font | Generic font |
---|---|---|
Arial | Arial | sans-serif |
Arial Black | Arial Black | sans-serif |
Comic Sans MS | Comic Sans MS | cursive |
Courier New | Courier New, Courier | monospace |
Georgia | Georgia | serif |
Impact | Impact, Charcoal | sans-serif |
Lucida Console | Monaco | monospace |
Lucida Sans Unicode | Lucida Grande | sans-serif |
Palatino Linotype | Palatino | serif |
Tahoma | Geneva | sans-serif |
Times New Roman | Times | serif |
Trebuchet MS | Trebuchet MS, Helvetica | sans-serif |
Verdana | Verdana, Geneva | sans-serif |
MS Sans Serif | Geneva | sans-serif |
MS Serif | New York | serif |
Using @font-face
Browsers have, for a long time, supported the @font-face
selector which allows you to define and provide a link to a web font stored on your server (if you are licenced to distribute it) or from a free or commercial online font library.
The CSS is fairly straightforward. First, you define the name you want to call the font and set its source location; for example:
@font-face { font-family: MyFont; src: url("/fonts/MyFont.otf"); }
Note: If you have multiple fonts to define, simply add additional @font-face
rules (don’t try to combine them within the same @font-face
rule).
Afterward, you can apply your font like any other; for example:
h1 { font-family: MyFont; }
Seems simple enough right? Unfortunately, there have been 2 major issues preventing web fonts to be easily used.
Web font format support
The first hurdle to overcome is browser support of web font formats.
Browsers have been slow to support a universal web font format. Although support has improved, there are still challenges with the current support status of the latest browsers:
- Embedded OpenType (.eot) - supported by Internet Explorer only
- TrueType/OpenType (.ttf/.otf) - long supported by most browsers, although only partially supported in Internet Explorer
- Web Open Font Format (.woff) - supported in recent versions of Chrome, Firefox, Internet Explorer and Safari.
While you can specify additional sources to provide alternative fonts, this can cause problems, especially for IE and a complex workaround is required.
Licencing issues
The second hurdle has to do with licencing issues.
Many fonts, whether free or paid for, usually have licencing agreements that prevent you from distributing (from your own server) or converting the font to different font formats.
Using online web font providers
The easiest way to overcome these issues is to use fonts provided by an online service that offers multiple-browser support, often by detecting the browser and then serving up the font in the most suitable format for each visitor to your site.
Of the numerous providers, many aim to sell you fonts—either per font or as a subscription to a font library. However, they often offer a small range of fonts for you to try for free or provide a free limited trial.
Do a search for the latest providers, also check out the following:
Each provider offers instructions telling you how to add their fonts to your site.
Applying italics
Use the following to italicise a font:
font-style: italic;
Applying bold weight
Use the following to display a font in bold:
font-weight: bold;
Alternatively, you can use the values: bolder or lighter to specify a relative weight.
Font size
There are a few different ways to specify font size:
- Exact size using pixels (
px
):
font-size: 18px;
- Keyword -
xx-small
,x-small
,small
,medium
,large
,x-large
,xx-large
:
font-size: small;
- Relative size (to body or parent element =
1em
or100%
):
font-size: 1.5em; font-size: 150%;
Using an exact pixel size provides you with precise control over your page design; however, this may prevent some users from changing the text size in their browser. Some browsers interpret keyword sizes differently—for example, some regard 'small' as the base font, while others use 'medium'.
16px is the default body size in most browsers.
Relative sizes will be based around this if any parent element that the text is contained in has no font-size
specified.
Line height
Line height (also known as 'leading' or 'line spacing') is the amount of space between lines of text. Increasing this from the default value can improve readability and make your page look more stylish. It can be specified as a percentage of the font size or as an exact pixel value. For example:
line-height: 150%; line-height: 20px;
Increasing the default line height can enhance the appearance of text as it makes it ‘lighter’ to read.
In this example, much larger line spacing coupled with the combined bold and italic styles gives the first paragraph more importance.
Combining font values
To reduce the amount of CSS code, you can set the font-style
, font-weight
, font-size
, line-height
and font-family
together using the font
property. For example:
font: italic bolder 18px / 22px Tahoma, Geneva, sans-serif; font: 85% Arial, sans-serif;
Note:
- The
font-size
andfont-family
values must always be specified and placed at the end. - The
font-style
andfont-weight
properties are optional and can be in any order, each one separated by a space only, or can be omitted. - The
line-height
is optional and is specified directly after thefont-size
, separated by a forward slash (/
).
As you have seen, all of the CSS values covered can be combined using the font
property.
The remaining formatting options must be added as separate property: value;
pairs, separated by semi-colons (;
) and placed within the curly brackets {}
; for example:
h1 { color: teal; font: 85% Arial, sans-serif; text-align: center; }
For clarity, it is also good practice to lay out your CSS code as follows:
h1 { color: teal; font: 85% Arial, sans-serif; text-align: center; }
Here is an example of styling tables with CSS:
form { width: 500px; padding: 1em; margin: 0 auto; border: 1px solid #ccc; border-radius: 1em; } ul { padding: 0; margin: 0; list-style: none; } form li + li { margin-top: 1em; } label { display: inline-block; width: 90px; text-align: right; } input, textarea { box-sizing: border-box; width: 300px; border: 1px solid #999; font: 1em sans-serif; } input:focus, textarea:focus { border-color: #000; } textarea { height: 5em; vertical-align: top; } .button { padding-left: 90px; } button { margin: 0; }
CSS is the language used to apply colour, positioning, and add styling to elements in an HTML document. In this topic, we covered how tags, classes and ids can be utilised to define the content and create meaningful groups that are selectable and styleable in CSS.
The following important concepts were also covered:
- The difference between display Block and Inline elements
- The CSS box model
- Cascading principles.
Many of the subtopics included interactive examples demonstrating how specific CSS properties are applied to HTML. You should go back and experiment by changing the values in the examples to see the results.
Knowledge check
Additional resources
Here are some links to help you learn more about this topic.
It is expected that you should complete 12 hours (FT) or 6 hours (PT) of student-directed learning each week. These resources will make up part of your own student-directed learning hours.
- CSS Code Generator
- W3Schools CSS
- CSS colors
- CSS Positioning Explained - By Nigel Buckner
- Position Property - By W3School
- "Play it" Positioning - By W3Schools
- CSS Overflow Property - By CSS-Tricks
- Overflow Property - BY W3Schools
- Inline-block Example - By W3Schools
- Display - By CSS Tricks
- CSS float vs display - By Stackoverflow
- Gradient Backgrounds - By W3Schools
- Gradients - By CSS-tricks
- Gradient Generator - By cssgradient
- Gradient Generator - By color space
- Background Images/Colours - By CSS Tricks
- 'Play it' Background-size - By W3Schools
- Image Placeholders
- Placeholder Kitten Images!
- Background Patterns - By heropatterns
- Patterns - By patternizer
- CSS Pattern generator - By patternify
- 15 Background & Pattern Generators - By WPShopsmart
- Background image tiles - By bgpatterns