In HTML5 we typically do not include HTML to how our page should look or stylize the layout; but instead we code the structure, content, layout, and organization. We use Cascading Style Sheets to define styling, looks, and quite often layout specifics, such as positioning, and implement concepts such as responsive design.
Once we understand the structure of CSS, we can often layer CSS in a particular way to create generic rules to how all similar elements of the design will look the same throughout an entire website, throughout an entire page, or be more specific to each individual tag and how it is to be displayed. This layering is one of the fundamental concepts of CSS.
CSS is made up of rules made up of two components:
{...}
For Example:
h1 {
color: blue;
font-size: 12px;
border-bottom: 1px solid black;
}
where the h1
is the selector, and the content inside the {curly braces} are the declarations made up of key/value pairs.
In this example, ALL h1
tags within the css scope will obtain this styling.
color: blue;
states that all h1 tags will be coloured blue.font-size: 12px;
says all h1 tags will be 12px in sizeborder-bottom: 1px solid black;
says we will add a border under the tag. Since an h1 tag is a block tag, the border will go the the right side of the current container.Here is another example:
p {
color: grey;
text-align: justify;
margin: 10px 5px 10px 5px;
}
This indicates that all p
tags within the the scope of the css will obtain these characteristics.
color: grey;
the paragraph will be grey colouredtext-align: justify;
the paragraph will be fully justified, a typical formatting for research or technical papersmargin: 10px 5px 10px 5px;
meaning the paragraph will have 10px margins on the top and bottom and 5 bx margins on the left and right.There are 4 locations where CSS can be present. The location of the CSS is hierarchal, meaning each subsequent location will overwrite the previous css where their are repeated selectors. The hierarchy of the locations (from least important to most important) are:
this CSS is applied by default when no styling has been provided.
Advanced developers have css code that neutralizes the default browser css such that they have complete control over the styling without the defaults interfering.
external .css
files can be references in the <head>
of the html document. If multiple files are included, each subsequent file is added and any repeated selectors declarations are overwritten. The advantage of separate files is that multiple pages in a website can share common css and therefore include a common look and feel without duplicating code on each page.
Files are included in the html using the following syntax:
<link rel="stylesheet" href="css/stylesheet.css" type="text/css">
<!-- as a local file or as an external reference: -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" type="text/css">
Additionally, external files reduce the css code included in the html files directly. These files can be cached by browsers and re-used on other pages without having to reload/download them.
style
tags can be added within the html document that contained css syntax. This css will apply only to the current page, and the the html after the embedded css. These embedding of css is typically found in the head section of the html page placed either before or after the external references to set the hierarchal order.
As mentioned above, this method of including css cannot be cached by browsers and must be reloaded each time, making each page in a web site have longer loading times. This css embedding method should only be used for general css declarations that apply only to the page they are embedded in.
Example:
<style>
h1 {
color: blue;
font-size: 12px;
border-bottom: 1px solid black;
}
p {
color: grey;
text-align: justify;
margin: 10px 5px 10px 5px;
}
</style>
Inline styling is located as attributes inside specific html tags. The css will apply to only the tag that it is located in.
For example:
<div style="background-color: green">...</div>
In advanced systems, and through OOP (Object Oriented Programming) techniques, css files can be embedded inside other css files, such that common declarations can be included in other css files.
/* Import Font Awesome */
@import url(https://use.fontawesome.com/releases/v5.4.2/css/all.css)
So far, this page has shown several different selectors, each typically representing a specific type of tag. This is only one type of selector that is possible, and in fact there are many different ways to indicate selectors.Although there are many types of selectors, the following are the most common ones:
Each of the above selector types is described in detail below.
The most common selector is the tag/type selector, that we indicate that all tags of the declared type will obtain the declared style rules.
Example:
h1 {
color: blue;
font-size: 12px;
border-bottom: 1px solid black;
}
p {
color: grey;
text-align: justify;
margin: 10px 5px 10px 5px;
}
These style declarations will apply to ALL matching tags within the scope of the css.
Often we will want to apply similar styling to some, but not all elements of a certain kind or a different kinds. Maybe we want to create a highlighting style that makes certain text a different colour regardless f the text is contained within different tags. We can code this by adding a class
attribute to the relevant tags where it will be implemented. Class selectors are declared in the css starting with a .
.
For Example
<style>
.highlight {
color: #ffcc00;
}
</style>
<p>The most <span class="highlight">important<span> content will be highlighted.</p>
<h1 class="highlight">Highlighted Heading</h1>
In the above example, the colour gold will be applied to the word important and the entire h1 title. All other text will follow defaults or any previously defined css.
A class can be applied to elements that aren't of the same type:
<style>
.invisible {
display: none;
}
</style>
<h1 class="invisible">Title</p>
<p class="invisible">This is a paragraph.</p>
An element can also have multiple classes applied, each one adding different styling:
<style>
.invisible {
display: none;
}
.example {
color: green;
background-color: red;
}
</style>
<p class="invisible example">This is a paragraph that uses two classes at once.</p>
In many cases, we have only a single element that should use styles. Using a type or class selector would be overly broad, and so we tend to use an id instead. Recall that only one HTML element in a document can have a given id attribute: it must be unique. ID Selectors are declared in the css beginning with the #
symbol
<style>
#summary {
background-color: skyblue;
}
</style>
<div id="summary"></div>
When we use the id as a selector, we prefix it with the # symbol. Notice that the HTML does not use the # symbol though.
A common way to declare selectors is to use the position of elements in the DOM (Document Object Model). The context selector indicates the context, or placement/nesting of tags within one another.
For example, if we want to apply styles to <p>
tags that are children of <div>
tags, the selector can be declared as follows:
<style>
div p {
font-size: 16px;
}
</style>
<p>This paragraph will not receive the styling</p>
<div>
<p>This paragraph will receive the styling.</p>
<p>This paragraph will receive the styling also.</p>
</div>
Quite often there will be more than one selector that will receive the same styling, especially when it comes to styles like font type. Therefore you can combine some selectors together such that multiple selectors will receive the same styling. This can be combined with separate selectors to declare the differences as well.
For example:
h1, h2 {
font-family: Serif;
color: blue;
}
h1 {
font-size: 2em;
}
h2 {
font-size: 1.6em;
}
In the above example, the first combined selector indicates that both h1 and h2 tags will be blue and use the same font "Serif". However, h1 and h2 tags will be different sizes based on the 2nd and 3rd selectors.
We've discussed <div>
and <span>
in the past, but their purpose may not have been clear. Why bother wrapping other elements in <div>
...</div>
or <span>
...</span>
when they don't display any different?
With CSS we can now start to take advantage of what they provide. If we think of them as containers which can be used to group styling, their purpose will become more clear.
A <div>
is a block level element, and <span>
an inline element. Depending on how we want to group and apply styling, we can use one or both. Consider the following:
<style>
.info-box {
border: solid green;
}
.info-box p {
font-family: Serif;
}
.info-box span {
font-weight: bold;
}
.info-box img {
width: 75px;
height: 75px;
}
</style>
<p>This paragraph won't have any special style applied. Neither will this <span>span</span>.</p>
<div class="info-box">
<p><span>Name:</span> Thomas Lee</p>
<p><span>Age:</span> 23</p>
<img src="tlee.jpg">
</div>
Many CSS values require units to be specified, for example, font sizes, widths, heights, etc. At first you might think that we should specify things in pixels; however, browsers need to work on such a wide variety of hardware and render to so many different displays (watches to billboards), we need more options. It's also important to be able to specify sizes using relative units vs. fixed, for layouts that need to adapt to changing conditions and still retain the correct proportions.
There is one exception, and that is for 0 (i.e., zero), which never needs a unit (i.e., 0px is the same as 0%, etc).
The most common units we use in CSS are:
1em = 12pt = 16px = 100%
Let's look at each of these in turn:
em
(the width of the capital letter M) - a scalable unit that is used in web media, and is equal to the current font-size. If the font-size is 12pt, 1em is the same as 12pt. If the font-size is changed, 1em changes to match. We can also use multiples: 2em is twice the font-size, and .5em is half. Using em for sizes is popular on the web, since things have to scale on mobile vs. desktop (i.e., fixed unit sizes don't work as the screen shrinks/expands).pt
- a fixed-size Point unit that comes from print media, where 1pt equals 1/72 of an inch.px
- pixels are fixed size units for web media (screens), and 1px is equal to one dot on a computer display. We use px on the web when we need “pixel perfect” sizing (e.g., image sizes).%
- the percent unit is similar to em in that it scales with the size of the display. 100% is the same as the current font-size.vw, vh
- the viewport width and height units are percentages of the visible space in the viewport (the part of the page you can see, the window's width and height). 1vw is the same as 1% of the width of the viewport, and 80vh is the same as 80% of the visible height.You will also sometimes encounter other ways of measurement that use full words: xx-small, x-small, small, medium, large, x-large, xx-large, smaller, larger, thin, medium, thick
Here's an example that uses a number of the units mentioned above:
<style>
html, body {
height: 100vh;
}
.box {
margin: 10px;
font-size: 2em;
height: 150px;
border: medium solid black;
}
</style>
<div class="box"></div>
CSS allows us to define colour values for many declarations. We do so by specifying a colour using one of the following notations:
The easiest way to understand this is using a Colour Picker tool, which lets you visually see the difference in changing values.
A property is assigned to a selector in order to manipulate its style. The CSS properties are defined as part of the CSS standard. When you want to know how one of them works, or which values you can assign, you can look at the documentation on MDN. For example:
text-indent
color
background-color
border
There are hundreds of properties we can tweak as web developers, and it's a good idea to explore what's available, and to look at how other web sites use them via the developer tools.
A property can have one or more values. A the possible values a property can have also comes from the standard. For example:
p {
text-decoration: underline;
}
.spelling-error {
text-decoration: red wavy underline;
}
The text-decoration property is defined to take one of a number of values, each of which is also defined in the standard.
By far the best way to learn about CSS is to look at how other sites use it. When you find something on the web that you think looks interesting, open your browser's dev tools and inspect the CSS Styles:
You can look at the specific properties specified for an element, or see all the computed styles (i.e., everything, including all default values). You can also try toggling these on and off, or double-click the values to enter your own.
There are dozens of properties that affect how text is rendered. These include things like the color, spacing, margins, font characteristics, etc.
h2 {
color: red;
text-align: center;
text-decoration: underline;
text-transform: uppercase;
}
p {
color: #0000ff;
text-indent: 100px;
}
We can use the font-family property to specify a font, or list of fonts, for the browser to apply to an element. The font must be available on the user's computer, otherwise the next font in the list will be tried until one is found that is installed, or a default font will be used.
In general it is safe to assume that the following fonts are available:
Helvetica, Arial, Verdana, sans-serif
- sans-serif fonts"Courier New", Courier, monospace
- monospace fontsGeorgia, "Times New Roman", Times, serif
- serif fontsYou can see a list of the fonts, and OS support here.
h3 {
font-family: Arial;
}
h4 {
font-family: "Times New Roman", Times, serif;
}
h5 {
font-size: 18pt;
font-style: italic;
font-weight: 500
}
Modern browsers also allow custom fonts to be included as external files, and downloaded as needed by the web site. This is often the preferred method for designers, who don't want to be limited to the set of fonts available on all operating systems.
A font is a file that describes the curves and lines needed to generate characters at different scales. There are various formats, from OTF (OpenType Format) to TTF (TrueType Format) to WOFF (Web Open Font Format), etc. In order for the browser to use a new font, it has to be downloadable via one or more URLs. We then tell the browser which font files to download in our CSS via the @font-face property:
@font-face {
font-family: "FontName"
src: url(font.woff2) format('woff2'),
url(font.ttf) format('truetype');
}
body {
font-family: "FontName";
}
Many fonts have to be purchased, but there are some good sources of high quality, freely available fonts for your sites:
For example, we can use the popular "Lobster" font from Google by doing the following in our CSS:
@import url(https://fonts.googleapis.com/css?family=Lobster)
p {
font-family: "Lobster";
}
Using the font-size property, font sizes can be given in fixed or relative units, depending on how we want our text to scale on different devices:
h1 {
font-size: 250% /* scaled to 250% of regular font size */
}
p {
font-size: 20pt /* size in points -- 20/72 of an inch */
}
.quote {
font-size: smaller; /* smaller than normal size */
}
.bigger {
font-size: 1.5em; /* 1.5 times larger than the 'M' in normal font size */
}
There are numerous effects that can be added to text (or any element), many beyond the scope of this initial exploration of CSS. Here are a few simple examples to give you an idea
text-shadow allows a shadow to be added to text, giving it a 3-D style appearance. The value includes a colour, x and y offsets that determine the distance of the shadow from the text. Finally, we can also add a blur-radius, indicating how much to blur the shadow.
.shadow-text {
text-shadow: 1px 1px 2px pink;
}
text-overflow can be used to determine what the browser should do when the amount of text exceeds the available space in a container (e.g. in a <div>
or <p>
that isn't wide enough). For example, we can specify that we want to clip the contents and not show any more, or we can automatically display ..., the ellipsis.
<style>
.movie-title {
text-overflow: ellipsis;
}
</style>
<span class="movie-title">Pirates of the Caribbean: The Curse of the Black Perl</span>
Every element has a background that we can modify. We might, for example, want to specify that the background be a certain colour; or we might want to use an image, or even tile an image multiple times (like wallpaper to create a pattern); or we might want to create a gradient, from one colour to another. All of these options and more are possible using the background property.
div.error {
background: red;
}
div.wallpaper {
background: url("pattern.jpg") repeat;
}
We can control the way that links (i.e., <a>
) appear in our document. By default they will have a solid blue underline, and when visited, a purple solid underline. If you want to remove the underline, or change it's colour to match the theme of a page, we can do that using CSS pseudo-classes.
With pseudo-classes we can specify certain states for the elements in our selector, for example:
a:link
- a normal, unvisited link (normally blue underline)a:visited
- a link the user has visited previously (normally purple underline)a:hover
- a link when hovered with the mousea:active
- a link when it is clicked (i.e., while the mouse button is pressed)NOTE: pseudo-classes can be used with any element, but we mention them here in relation to styling links, since we often need them to deal with different states for a link.
Let's alter our links so that they use blue text, with no underline. However, when hovered, add back the underline:
a:link, a:visited {
text-decoration: none;
}
a:hover, a:active {
text-decoration: underline;
}