CSS : Cascading Style Sheets
A handy guide to CSS for developers
What is CSS?
Cascading Style Sheets (CSS) is a stylesheet language used to describe the presentation of a document written in HTML or XML (including XML dialects such as SVG, MathML or XHTML). CSS describes how elements should be rendered on screen, on paper, in speech, or on other media. CSS is one of the core languages of the open Web and is standardized across Web browsers. Previously development of various parts of CSS specification was done synchronously, which allowed versioning of the latest recommendation. You might have heard about CSS1, CSS2.1, CSS3. However, CSS4 has never become an official version.
CSS (Cascading Style Sheets) is used to style and layout web pages — for example, to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features. This module provides a gentle beginning to your path towards CSS mastery with the basics of how it works, what the syntax looks like, and how you can start using it to add styling to HTML.
ADDING CSS TO AN HTML PAGE
CSS is attached to an HTML page in different ways.
1: Using the link
tag
The link
tag is the way to include a CSS file. This is the preferred way to use CSS as it's intended to be used: one CSS file is included by all the pages of your site, and changing one line on that file affects the presentation of all the pages in the site.
To use this method, you add a link
tag with the href
attribute pointing to the CSS file you want to include. You add it inside the head
tag of the site (not inside the body
tag):
<link rel="stylesheet" type="text/css" href="myfile.css">
The rel
and type
attributes are required too, as they tell the browser which kind of file we are linking to.
2: using the style
tag
Instead of using the link
tag to point to separate stylesheet containing our CSS, we can add the CSS directly inside a style
tag. This is the syntax:
<style>
...our CSS...
</style>
Using this method we can avoid creating a separate CSS file. I find this is a good way to experiment before “formalising” CSS to a separate file, or to add a special line of CSS just to a file.
3: inline styles
Inline styles are the third way to add CSS to a page. We can add a style
attribute to any HTML tag, and add CSS into it.
<div style="">...</div>
Example:
<div style="background-color: yellow">...</div>
SELECTORS
A selector allows us to associate one or more declarations to one or more elements on the page.
Basic selectors
Suppose we have a p
element on the page, and we want to display the words into it using the yellow color.
We can target that element using this selector p
, which targets all the element using the p
tag in the page. A simple CSS rule to achieve what we want is:
p {
color: yellow;
}
Every HTML tag has a corresponding selector, for example: div
, span
, img
.
If a selector matches multiple elements, all the elements in the page will be affected by the change.
HTML elements have 2 attributes which are very commonly used within CSS to associate styling to a specific element on the page: class
and id
.
There is one big difference between those two: inside an HTML document you can repeat the same class
value across multiple elements, but you can only use an id
once. As a corollary, using classes you can select an element with 2 or more specific class names, something not possible using ids.
Classes are identified using the .
symbol, while ids using the #
symbol.
Example using a class:
<p class="dog-name">
Roger
</p>.dog-name {
color: yellow;
}
Example using an id:
<p id="dog-name">
Roger
</p>#dog-name {
color: yellow;
}
Combining selectors
So far we’ve seen how to target an element, a class or an id. Let’s introduce more powerful selectors.
Targeting an element with a class or id
You can target a specific element that has a class, or id, attached.
Example using a class:
<p class="dog-name">
Roger
</p>p.dog-name {
color: yellow;
}
Example using an id:
<p id="dog-name">
Roger
</p>p#dog-name {
color: yellow;
}
Why would you want to do that, if the class or id already provides a way to target that element? You might have to do that to have more specificity. We’ll see what that means later.
Targeting multiple classes
You can target an element with a specific class using .class-name
, as you saw previously. You can target an element with 2 (or more) classes by combining the class names separated with a dot, without spaces.
Example:
<p class="dog-name roger">
Roger
</p>.dog-name.roger {
color: yellow;
}
Combining classes and ids
In the same way, you can combine a class and an id.
Example:
<p class="dog-name" id="roger">
Roger
</p>.dog-name#roger {
color: yellow;
}
Grouping selectors
You can combine selectors to apply the same declarations to multiple selectors. To do so, you separate them with a comma.
Example:
<p>
My dog name is:
</p>
<span class="dog-name">
Roger
</span>p, .dog-name {
color: yellow;
}
You can add spaces in those declarations to make them more clear:
p,
.dog-name {
color: yellow;
}
Follow the document tree with selectors
We’ve seen how to target an element in the page by using a tag name, a class or an id.
You can create a more specific selector by combining multiple items to follow the document tree structure. For example, if you have a span
tag nested inside a p
tag, you can target that one without applying the style to a span
tag not included in a p
tag:
<span>
Hello!
</span>
<p>
My dog name is:
<span class="dog-name">
Roger
</span>
</p>p span {
color: yellow;
}
See how we used a space between the two tokens p
and span
.
This works even if the element on the right is multiple levels deep.
To make the dependency strict on the first level, you can use the >
symbol between the two tokens:
p > span {
color: yellow;
}
In this case, if a span
is not a first children of the p
element, it's not going to have the new color applied.
Direct children will have the style applied:
<p>
<span>
This is yellow
</span>
<strong>
<span>
This is not yellow
</span>
</strong>
</p>
Adjacent sibling selectors let us style an element only if preceded by a specific element. We do so using the +
operator:
Example:
p + span {
color: yellow;
}
This will assign the color yellow to all span elements preceded by a p
element:
<p>This is a paragraph</p>
<span>This is a yellow span</span>
We have a lot more selectors we can use:
- attribute selectors
- pseudo class selectors
- pseudo element selectors
We’ll find all about them in the next sections.
CASCADE
Cascade is a fundamental concept of CSS. After all, it’s in the name itself, the first C of CSS — Cascading Style Sheets — it must be an important thing.
What does it mean?
Cascade is the process, or algorithm, that determines the properties applied to each element on the page. Trying to converge from a list of CSS rules that are defined in various places.
It does so taking in consideration:
- specificity
- importance
- inheritance
- order in the file
It also takes care of resolving conflicts.
Two or more competing CSS rules for the same property applied to the same element need to be elaborated according to the CSS spec, to determine which one needs to be applied.
Even if you just have one CSS file loaded by your page, there is other CSS that is going to be part of the process. We have the browser (user agent) CSS. Browsers come with a default set of rules, all different between browsers.
Then your CSS comes into play.
Then the browser applies any user stylesheet, which might also be applied by browser extensions.
All those rules come into play while rendering the page.
We’ll now see the concepts of specificity and inheritance.
SPECIFICITY
What happens when an element is targeted by multiple rules, with different selectors, that affect the same property?
For example, let’s talk about this element:
<p class="dog-name">
Roger
</p>
We can have
.dog-name {
color: yellow;
}
and another rule that targets p
, which sets the color to another value:
p {
color: red;
}
And another rule that targets p.dog-name
. Which rule is going to take precedence over the others, and why?
Enter specificity. The more specific rule will win. If two or more rules have the same specificity, the one that appears last wins.
PSEUDO-CLASSES
Pseudo classes are predefined keywords that are used to select an element based on its state, or to target a specific child.
They start with a single colon :
.
They can be used as part of a selector, and they are very useful to style active or visited links, for example, change the style on hover, focus, or target the first child, or odd rows. Very handy in many cases.
These are the most popular pseudo classes you will likely use:
Let’s do an example. A common one, actually. You want to style a link, so you create a CSS rule to target the a
element:
a {
color: yellow;
}
Things seem to work fine, until you click one link. The link goes back to the predefined color (blue) when you click it. Then when you open the link and go back to the page, now the link is blue.
Why does that happen?
Because the link when clicked changes state, and goes in the :active
state. And when it's been visited, it is in the :visited
state. Forever, until the user clears the browsing history.
So, to correctly make the link yellow across all states, you need to write
a,
a:visited,
a:active {
color: yellow;
}
:nth-child()
deserves a special mention. It can be used to target odd or even children with :nth-child(odd)
and :nth-child(even)
.
It is commonly used in lists to color odd lines differently from even lines:
ul:nth-child(odd) {
color: white;
background-color: black;
}
You can also use it to target the first 3 children of an element with :nth-child(-n+3)
. Or you can style 1 in every 5 elements with :nth-child(5n)
.
Some pseudo classes are just used for printing, like :first
, :left
, :right
, so you can target the first page, all the left pages, and all the right pages, which are usually styled slightly differently.
PSEUDO-ELEMENTS
Pseudo-elements are used to style a specific part of an element.
They start with a double colon ::
.
Sometimes you will spot them in the wild with a single colon, but this is only a syntax supported for backwards compatibility reasons. You should use 2 colons to distinguish them from pseudo-classes.
::before
and ::after
are probably the most used pseudo-elements. They are used to add content before or after an element, like icons for example.
Here’s the list of the pseudo-elements:
Let’s do an example. Say you want to make the first line of a paragraph slightly bigger in font size, a common thing in typography:
p::first-line {
font-size: 2rem;
}
Or maybe you want the first letter to be bolder:
p::first-letter {
font-weight: bolder;
}
::after
and ::before
are a bit less intuitive. I remember using them when I had to add icons using CSS.
You specify the content
property to insert any kind of content after or before an element:
p::before {
content: url(/myimage.png);
}.myElement::before {
content: "Hey Hey!";
}
BACKGROUNDS
The background of an element can be changed using several CSS properties:
background-color
background-image
background-clip
background-position
background-origin
background-repeat
background-attachment
background-size
and the shorthand property background
, which allows us to shorten definitions and group them on a single line.
COMMENTS
CSS gives you the ability to write comments in a CSS file, or in the style
tag in the page header
The format is the /* this is a comment */
C-style (or JavaScript-style, if you prefer) comments.
This is a multiline comment. Until you add the closing */
token, the all the lines found after the opening one are commented.
Example:
#name { display: block; } /* Nice rule! *//* #name { display: block; } */#name {
display: block; /*
color: red;
*/
}
FONTS
At the dawn of the web you only had a handful of fonts you could choose from.
Thankfully today you can load any kind of font on your pages.
CSS has gained many nice capabilities over the years in regards to fonts.
The font
property is the shorthand for a number of properties:
font-family
font-weight
font-stretch
font-style
font-size
BORDER
The border is a thin layer between padding and margin. By editing the border, you can make elements draw their perimeter on screen.
You can work on borders by using those properties:
border-style
border-color
border-width
The property border
can be used as a shorthand for all those properties.
border-radius
is used to create rounded corners.
You also have the ability to use images as borders, an ability given to you by border-image
and its specific separate properties:
border-image-source
border-image-slice
border-image-width
border-image-outset
border-image-repeat
PADDING
The padding
CSS property is commonly used in CSS to add space in the inner side of an element.
Remember:
margin
adds space outside an element borderpadding
adds space inside an element border
Specific padding properties
padding
has 4 related properties that alter the padding of a single edge at once:
padding-top
padding-right
padding-bottom
padding-left
The usage of those is very simple and cannot be confused, for example:
padding-left: 30px;
padding-right: 3em;
Specific margin properties
margin
has 4 related properties that alter the margin of a single edge at once:
margin-top
margin-right
margin-bottom
margin-left
The usage of those is very simple and cannot be confused, for example:
margin-left: 30px;
margin-right: 3em;
Which Properties You Can Animate using CSS Animations
A lot! They are the same you can animate using CSS Transitions, too.
Here’s the full list:
background
background-color
background-position
background-size
border
border-color
border-width
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-width
border-left
border-left-color
border-left-width
border-radius
border-right
border-right-color
border-right-width
border-spacing
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-width
bottom
box-shadow
caret-color
clip
color
column-count
column-gap
column-rule
column-rule-color
column-rule-width
column-width
columns
content
filter
flex
flex-basis
flex-grow
flex-shrink
font
font-size
font-size-adjust
font-stretch
font-weight
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column-end
grid-column-gap
grid-column-start
grid-column
grid-gap
grid-row-end
grid-row-gap
grid-row-start
grid-row
grid-template-areas
grid-template-columns
grid-template-rows
grid-template
grid
height
left
letter-spacing
line-height
margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
min-height
min-width
opacity
order
outline
outline-color
outline-offset
outline-width
padding
padding-bottom
padding-left
padding-right
padding-top
perspective
perspective-origin
quotes
right
tab-size
text-decoration
text-decoration-color
text-indent
text-shadow
top
transform.
vertical-align
visibility
width
word-spacing
z-index
Some of the Rarely Used CSS Properties
Perspective Property:
The perspective property is used to activate the three-dimensional space on an element so that its children can be positioned in that space.
Syntax:- perspective: length|none|initial|inherit;
Object-Fit Property:
The object-fit property specifies how the contents of a replaced element should be fitted to the box and established by its used height and width.
Syntax:- object-fit: fill|contain|cover|none|scale-down;
Shape-Outside Property:
The shape-outside provides a way to customize the content wrapping, making it possible to wrap text around complex objects rather than simple boxes.
Syntax:- shape-outside: none|[<basic-shape>||,shape-box>]|<image>;
Caret-Color Property:
The caret-color CSS property sets the color of the insertion caret, the visible marker where the next character typed will be inserted.
Syntax:- caret-color: auto|color;
Orphans Property:
The orphans CSS property sets the minimum number of lines in a block container that must be shown at the bottom of a page, region or column.
Syntax:- orphans: <integer> | inherit;
WRAPPING UP
I hope this article helped you get up to speed with CSS and get an overview of the main features you can use to style your pages and apps. I wrote it to help you get comfortable with CSS and get you quickly up to speed with using this awesome tool that lets you create stunning designs on the Web, and I hope I achieved with this goal.