CSS Tutorial: William R
CSS Tutorial: William R
William R.
Introduction
Definition
CSS stands for Cascading Style Sheet. It’s used to style and layout of a website. It works alongside HTML.
Inline CSS
We can add CSS code directly into our HTML file by using the style attribute inside a HTML tag. For in-
stance, in order to change the background color of the page, we’d use:
Internal CSS
We can also add CSS code directly into our HTML by setting up a distinct section of the file specifically
to write CSS code. This is done by nesting the <style></style> tag inside the <head></head> tag of the HTML
file. Using an internal CSS file is preferable to inline CSS because any changes made inside the CSS file are
applicable across multiple elements. Copying and pasting inline CSS code is error-prone and harder to debug.
<html>
<head>
<style>
body {
background-color: blue;
</style>
</head>
<body>
...
</body>
</html>
1
External CSS
Internal CSS becomes quite cumbersome when you have multiple pages in your website. An alternative is
to use a separate CSS file where you can store every single stylistic change you want to make across your web
pages.
A CSS file can be created by adding the .css extension. By convention, usually a new folder inside the folder
containing your website’s pages is created, called css, and within this folder, a new .css file called styles.css is
created. So the path to your .css file becomes: css/styles.css. Inside a HTML file, we can link to a CSS file by
adding a link tag inside the head portion of the document; add the rel="stylesheet" relationship attribute;
in the href attribute, add the path to your CSS file.
Test if the link is working by writing a property inside your CSS file that makes an obvious change (such as
changing the background color to red).
body {
background: red;
You need to go through this process of linking your CSS file in every single page hosted on your website.
Any piece of CSS code has the following elements: a selector that targets which HTML we want to design, a
block with curly braces, and property-value pairs that actually define the changes we want to make contained
within the block. The property is separated from its value with a colon : and each value must end with a
semi-colon;.
For instance:
However, by convention, we put each property in its own line. This is because once you have too many
property-value pairs, it becomes too convoluted having everything in a single line.
selector {
property1: value1;
property2: value2;
By convention, you should also look to list every property in alphabetical order; this becomes more im-
portant once you have too many property listed for a single selector, and it becomes quite difficult finding a
particular property you want to modify. Having them in alphabetical order makes it a lot easier to find prop-
erties.
2
Adding Comments
Comments can be added to your CSS code by using forward slashes and stars.
CSS Selectors
Selectors are a way of grabbing and manipulating HTML elements, and then styling them.
Element Selector
This type of selector applies the styling options to all the elements with the tag on the page. To use it, type
the name of the element (for instance, p for paragraph), and within curly braces, specify the property you want
to change and the value you want to set it to, separated by a colon (:).
p {
color: red;
Class Selector
In order to target a HTML element with a specific class attribute, simply introduce a dot (.) before the name
of that class as a selector in CSS. The styling options defined this way will only be applied to items that belong
to that specific class.
.aclass {
color: blue;
Apply the class attribute to HTML tags of the same type that you want to differentiate. For instance, if you
have two images and you want them to have a different background color, add a class attribute to each img
tag with a different identifier. That way, you can select and style different images by their distinct class name,
using the aforementioned syntax.
The same HTML element can contain multiple classes. These go under the same class attribute and are
separated by spaces. In CSS, there’s no change in the way you refer to elements containing multiple classes.
Simply refer to it using one of its classes.
3
ID Selector
Works very similarly to the class selector, but the name of the ID is preceded by a hash (#) instead of a dot
(.). It can only be used on one element at a time.
#sometext {
color: orange;
There are several different selectors available to choose. How to know when to use one over the other?
The difference between selectors lies in their specificity, or in other words, their ability to override properties
that were already set to a specific element. For example, if you had 2 properties applied to the same element,
by two different selectors, the most specific or ”powerful” selector would override the properties that were
defined by the less ”powerful” selector.
In descending order of specificity we have: in-line styling, ID selector, class selector and element selector.
The difference between a HTML class and HTML id is that a class is meant to be used when you want to
apply a style to a group of related items, whereas an id is meant to be used to specifically style a single item.
An id is supposed to be unique across the entire HTML document, e.g., if you have an element with id="name"
you cannot apply the attribute id="name" to any other tag. However, if you had a class called class="name" you
can indeed include it in as many elements as you’d like.
If you want to select multiple elements and apply the same general styling rules to all of them, simply write
the selector for each element, separated by a comma ,. The syntax looks like this (the space is optional but
good for readability):
selector1, selector2 {
In the example below we apply the same font family to h1 through h6 elements.
font-family: Montserrat;
4
Hierarchical Selectors
Mixing CSS selectors allows for application of styles more specifically. To do that, you have to target both
the parent and child elements, separated by a space. The syntax is as follows, where selector1 is the parent
element and selector2 is the child element:
selector1 selector2 {
In the example below we apply a specific type of padding to the container-fluid class inside the id title.
#title .container-fluid {
padding-top: 1%;
Combined Selectors
This style of selector applies a specific style only to the HTML that has both selectors (these selectors
must occur in the same element). Unlike the previous section, this syntax does not involve any parent-child
relationship. The syntax is as follows:
selector1selector2 {
For example, if selector1 is a HTML tag and selector2 is a HTML class, we would write:
selector1.selector2 {
In the example below we are specifying that we want the div with class container-fluid to have a text color
of red.
Pseudoselectors
Definition
HTML elements can have different states. For instance, by hovering over an element with your cursor,
you might introduce a change of style for that particular element. This change of state is done by using a
pseudoselector.
A pseudoselector goes together with a regular selector and changes the styling of an element, when
something specific is done on the page. For instance, if we want to change the color of the font when the
5
user hovers over the h2 tags of the page, add the hover pseudoselector. Every pseudoselector begins with a
colon, : to separate it from its selector.
h2:hover {
color: red;
One way to change the styling options for a child tag is by using the first-child and last-child pseudos-
electors. For instance, if we have a list of items (ol or ul), and we want to modify the last item of that list, we
can write:
li:last-child {
color: steelblue
To change a child that is neither the first nor the last, add the nth-child(n) pseudoselector, where n indicates
the number of the child. So for a list of three items, if we want to change the second, write:
li:nth-child(2) {
color: steelblue;
If a tag only has a single child, to modify the child we can use the only-child pseudoselector.
These pseudoselectors change the way a link looks before and after a user has visited the link/clicked on
the link. The two main pseudoselectors that control this are: link (unvisited link) and visited.
#google-link:link {
color: blue;
#google-link:visited {
color: red;
6
Advanced Selectors
Adding a style to all elements that follow another is a possibility in CSS. Suppose we want to apply the
same style to all a tags that come after an h2 tag.
h2 + a {
color: red;
General sibling selector works similarly to the previous selector, but all elements have to be sharing the same
parent tag. Suppose we want to style every button after the text area tag.
textarea ~ button {
color: purple;
The child selector styles every single direct child element inside a parent tag. If we want to apply some sort
of styling to every item of an unordered list:
ul > li {
color: blue
The descendent selector applies styling options to the child elements as well as their children. So if we have
two items inside an unordered list, and one of those items is itself an ordered list, the following piece of code
will color all items green.
ul li {
color: green;
Attribute Selectors
These selectors allows for selection of certain elements according to their tag and attribute. The general
syntax is:
tag_name[attribute=value] {
color: blue;
Let’s say we want to color all h2 tags that have the class="subtitle" attribute. Unlike in HTML, quotation marks
are not needed for the attribute value. It would look like this:
7
h2[class=subtitle] {
color: green;
To select all of the images found inside a particular folder, we need to start by specifying the value of the src
attribute as the relative path to the folder containing the images. On top of that, we need to add the ^ sign
before the = sign to make it apply to all images whose source start with that particular value, or the $ to make
it apply to all images whose source end with that particular value.
img[src^="../img/"] {
Coloring Properties
Definition of properties
Properties are defined within the selectors and they specify the way CSS is used to style the selected
item(s). A colon comes after the property name, followed by a value. After specifying all properties and values,
end with a semicolon.
Coloring basics
There are three different ways to color objects in CSS: CSS color name, hex code, and RGB code.
Google provides a color picker that comes with both Hex and RGB codes. To access it, simply type ”color
picker” into Google Search.
In Hex code, each code starts with # followed by 6 digits; numbers can go from 0 to 9, but also you can use
letters, that go from ”a” to ”f” and that have a ”numerical” value associated. The six digits that come after #
are grouped in pairs of three categories that indicate the amount of red, green and blue present in the color.
Having a ”00” indicates none of that color is present whereas ”FF” indicates the full intensity of that color is
present. So the color full color blue, for instance, is given by the code #0000FF because there’s no red, no
green, and only blue.
In RGB code, there are three numbers, the first for red, the second for green and third for blue. The num-
bers can go from 0 to 255 (maximum). So the color that we exemplified before in hex, #0000FF, is represented
by (0, 0, 255) in RGB.
Coloring text
To color text, type the selector and type color, and choose a color from a color picker; copy and paste the
hex or RGB code.
8
# title {
color: #ba8509;
It’s preferable to choose RGB over hex because RGB is easier to change and more flexible overall.
# title {
color: rgb(186,133,9);
Coloring backgrounds
Background colors are applied similarly to text colors. All html text is inside the body tag. So we can use
an element selector to paint all the background of the page. We can use either the background-color property
or the background property. The latter is much more flexible because it also allows for images to be placed.
body {
background: rgb(204,229,255);
To add an image as a background, we need to add a link to the image (URL as a web address or path to the
image if it’s stored in your computer). To get the link to an image from a website, right click on it and click on
”copy image address”. Put the URL inside the function url() in quotation.
body {
background: url("img_url");
The background-repeat controls whether an image is repeated multiple times to fill a certain width and
height requirement. Set it equal to no-repeat if you don’t want the image to be repeated and repeat (default
value) if you do.
#service-image {
height: 400px;
width: 70%;
background: url("img_url");
background-repeat: no repeat;
9
We can alter the size of the background by using the property background-size. The first value is the height
separated by the second value which is the width.
#service-image {
height: 400px;
width: 70%;
background: url("img_url");
background-repeat: no repeat;
You might find it difficult to figure out a combination of values that covers the pre-determined space. This
can be made easier by using the keyword cover. The image will take up the entire space available, however
there might be some compromise in its quality. The keyword contain resizes the image without changing the
proportions (aspect ratio).
#service-image {
height: 400px;
width: 70%;
background: url("img_url");
background-repeat: no repeat;
background-size: cover;
To add the option of control of the transparency/opacity, replace the rgb function for rgba, and add an-
other argument to this function, right after the blue color number, between 0 and 1, 0 meaning completely
transparent and 1 completely visible or opaque. This fourth component is called the alpha value.
body {
background: rgba(204,229,255,0.4);
Gradient
A gradient is a transition between two or more colors. There are two types of gradients: radial (circular) or
linear (smooth transition, from left to right, top to bottom or diagonally).
To add a linear gradient, set the value of background property to linear-gradient. The first argument of
this function is the direction, starting with the word to to specify the direction we want the colors to go. After
that, in the other arguments, include as many colors as you’d like; you can use RGB and RGBA as well.
10
#service-image {
height: 400px;
width: 70%;
background-size: cover;
To make a diagonal linear gradient, you will need to specify two directions after the word to. For instance,
if you want a diagonal gradient from the top left to bottom right, we’d add:
#service-image {
height: 400px;
width: 70%;
background-size: cover;
Another way to do diagonal linear gradients is by specifying the angle. Instead of typing to direction, type in
the number followed by the word deg.
#service-image {
height: 400px;
width: 70%;
background-size: cover;
Radial gradients are created with the radial-gradient function. Specify the colors as arguments. You can
specify the proportions of each color with percentages, but they must be in order, meaning the minimum
percentage has to be the first and the maximum percentage has to be the last. Additionally, you can specify
which shape you want the radial gradient to look like; the default shape is ellipse.
#service-image {
height: 400px;
width: 70%;
Types of Units
Absolute units always have a specific size, no matter the display it’s being used to showcase them. Exam-
ples include centimeters, inches, pixels and points (pt).
11
Relative units will adapt well to the size of the web page or the device being used to display them. They
are extremely useful to achieve a responsive web page that works across multiple devices. They are:
• Percentage: size of the element relative to its parent element, e.g. the width of the image is 70% of the
body of the text in the previous examples.
• em: Historically, this was the size relative to the current size of the uppercase letter M for the font being
used but nowadays it has the same meaning as the percentage.
• vw (view width): represents 1% of the total body width of the HTML document.
• vh (view width): represents 1% of the total body height of the HTML document.
Text manipulation
Includes changes that do not depend on the font. By default, anchor tags have an underline text decora-
tion. The options for text decorations are: none (removes any lines if they were present by default), underline,
overline and line-through.
.link {
text-decoration: line-through;
The text-transform property has three options: capitalize, uppercase and lowercase. Capitalizes makes the
first letter of each letter on the page be an uppercase letter as in the first letter that starts after a period, and
lowercase/uppercase are self-explanatory. The following piece of code will make the whole text in the web
page be uppercase.
body {
text-transform: uppercase;
The text-align property allows for control over the alignment of text. The options are: right, left, center and
justify, and these work just as they would in any text editor like Microsoft Word.
body {
text-transform: uppercase;
text-align: justify;
12
Font manipulation
The size of the font can be changed with the font-size property. One advantage of using a relative font
size, is that the scaling will be appropriate across devices and browser settings. A 100% font size or 1em is
equivalent to a 16px absolute font size. So, 100% = 1em = 16px.
body {
font-size: 1.25em;
However when you change the font size using a relative value, the resulting size will be affected by the font
size chosen in the parent element. If you have a h1 tag with font-size= 3em;, it will look much bigger if you
also have a body tag with font-size = 2em;, because in this case the 2 em from the body is added on top of
the 3 em defined in the heading.
One way to avoid this in CSS3 is by using rem instead of em; rem stands for ”root” em, and will override any
changes made by the parent element. Using rem instead of the regular em or percentage is recommended
because it’s more adaptable and less error-prone.
The font-weight property spans from 0 to about 800/900 for most fonts (in theory they can be as big as
you’d like but at some point there won’t be any more changes) and it controls the boldness of the font.
body {
font-weight: 800;
The font-style property is used for italicizing the font. There are three different options: normal (it’s the
upright regular font), italic, and oblique (more italicized than italic).
body {
font-style: oblique;
Font Families
A font family is a collection of fonts with similar features; the three main font families are: serifs, sans
serifs and monospaced. Sans serifs fonts are cleaner to read on a screen whereas serifs are commonly used
for printed text. Monospaced fonts have each letter occupy the same amount of horizontal space. There are
other font families such as cursive and fantasy, but you won’t be using these to style a website.
body {
font-family: sans-serif;
13
Within this same property we can also specify the font we want to use on the page. If a font has whitespaces
in its name, quotation marks are required, such as "Times New Roman". The following piece of code changes
the font for the body of the page as Times New Roman. If for some reason this font is unavailable and cannot
be rendered, it’s changed to the default serif font defined in the user’s web browser.
body {
There exists a group of fonts that are available in most operating systems and that the user’s browser
should have no problem rendering. These are called ”Web Safe Fonts”, and include Arial, Helvetica etc. Al-
though these fonts are named ”web safe” there are no fonts that are 100% web safe. In the CSS Font Stack
website you can see the statistics for fonts according to the user’s operating system.
External Fonts
In this example, open up Google Fonts and pick a font. From the font page, select a font family. There are
over 1000 to choose from in this website. Then, on the font page, select a style (light, medium, italic, etc).
Keep in mind that the more styles you select, the longer it will take to load the page, because there are more
requests to be sent.
Google fonts provides a tab called embed where we see an HTML code and CSS code. Copy the HTML
code with the link tag to the head of your HTML document. Post it above the style sheet. For instance:
<head>
</head>
By linking your web page to google fonts it makes sure that, in case the user does not have the fonts you
want to use already installed in their system, then the browser will grab the fonts from the location specified
in the href attribute.
After that, copy the CSS code from Google Fonts and paste it in your CSS file. Google already includes
the fall-back font (sans-serif) in case the select font can’t load.
body {
14
Stacking Order
Every element in CSS not only has X and Y coordinates but also a Z coordinate that dictates its depth in
relationship to the remaining elements on the page. The elements that come first in the HTML will be, by
default, farther away from the screen. Elements that come after will stack on top of one another.
One way to change the stacking order is by changing the order of the elements in HTML, but the best way
to do it is through the CSS property z-index. The default value for this property is 0. Also, the z-index only
works with absolute, fixed or relative positioning property (it will not work with the default position: static;
value).
Introduction
The box model is one way to design the layout of a website. In this model, every single element in HTML is
surrounded by an invisible box, and every box is connected. We can change the way the boxes are positioned,
and hence change the way the website looks, using CSS to style these boxes.
The model has the following parts, starting from the inner part to the outer part: content, padding, border,
margin. Each layer can be stretched and sized either symmetrically or asymmetrically.
The padding represents the space between the content and the border of the content, giving more room
around the content itself. The border separates the padding from the margin. By default you will see no
border, but that can be changed using the CSS property called border. The margin moves the content around
and give it space between other elements, adding external space around the box, whereas the padding adds
internal space to the box.
Usually it’s recommended to define the height as an absolute measurement and the width as a relative
measurement (varies from device to device). Suppose we have an image with the ID ”about-us-image”.
#about-us-image {
height: 300px;
width: 60%;
Manipulating Borders
The main general property to change the border is called border, with three options: size, style and color
in order and separated by one space. The main style options are dotted, dashed, solid and double; the most
common is solid. Color can be RGB or Hex. The following piece of code creates a solid black border around
15
the image. There’s no padding, because there’s no space between the image and the border, and the border
is touching other elements in the page (there’s no margin).
#about-us-image {
height: 300px;
width: 60%;
To manipulate the padding, use the padding property. If you add only one value, this amount of padding
will be applied to all sides of the image (top, bottom, left and right).
#about-us-image {
height: 300px;
width: 60%;
padding: 10px;
If you want to specify the amount of padding for one side in particular, add a dash followed by the side you
want to change, in the name of the property. For instance, to change the amount of padding in the right side
of the image we would use:
#about-us-image {
height: 300px;
width: 60%;
padding-right: 40px
Another option, instead of writing padding- is to write all of the sizes in the padding property, separated by
whitespaces, going in the order: top, right, bottom, left (clockwise rotation). To add 100px of padding to the
top, 40px to the right, none for the left side, and 5px to the bottom, we would need to write:
#about-us-image {
height: 300px;
width: 60%;
16
If you list only two values, the first value means top-bottom, and the second value means left-right. To make
the image have a 80px padding on the top and bottom, and a 40px padding on the left and right:
#about-us-image {
height: 300px;
width: 60%;
To manipulate the margin, use the margin property. It helps to separate the content, moving the image around
the page. This property works the same way as the padding property.
#about-us-image {
height: 300px;
width: 60%;
margin: 10px;
Float Property
The float property changes the way the element floats on the page, making it so that text can wrap around
images, so that images and text can both coexist in the same line. It also affects the remaining elements of
the page. The main float values are:
• right
• left
• inherit: makes it so that every child element inherits the float property defined for the parent. It’s useful
for not having to define a float property for child elements.
• none: it’s default value if nothing is specified, leaving the content where it naturally occurs in the text.
#about-us-image {
height: 300px;
width: 60%;
margin: 10px;
float: right;
If you want to remove the text wrapping for a particular piece of text, target it using the appropriate selector
and set its clear property to the same value as the float. Setting clear: left; clears the left margin of that
element and makes sure there’s nothing wrapping around it.
17
Display Property
The display property changes the default display of an HTML element. The values that can be applied are:
• none: the box that contains the element is gone from the page although it still exists in the code.
• inline: the element only takes up as much space as it needs to. Inline elements do not block other
elements from occurring in the same line as them. The most common HTML elements that have an inline
display by default are: spans, anchors. The width of these elements is fixed and cannot be changed.
• block: the element takes up the entire width of the screen, ”blocking out” other elements from sitting
next to it. The most common HTML elements that have a block display by default are: paragraphs,
headers, divs, lists, list items and forms. The width of these elements can be changed using the property
width.
• inline-block: it takes features from both inline and block display types, combining them together; it
doesn’t move the element to a new line, so in a way the element behaves like an inline element, however it
allows the width of the element to be changed, such that the element also behaves like a block element,
hence the name inline-block. The most common HTML element that has, by default, an inline-block
display type is image.
With the display property, we can make it so a p tag behaves like a span tag, by changing its default value
from block to inline.
Position Property
There are four main values that can be assigned to the position property:
• Static: all HTML elements are static by default. Setting display: static; will make it so that the display
rules are dictated by HTML.
• Relative: allows the positioning of elements relative to the default static position, using a coordinate
system comprised of top, bottom, left and right values. Note that changing one element will not affect
the layout of the remaining elements of the screen, meaning you may end up with overlapping elements
if you do not change the positioning of the other elements.
• Absolute: the element is positioned according to the relative position of its parent element. This type of
positioning affects the flow of the remaining elements as well.
• Fixed: the element remains in its position even when you scroll down or up the page. This is useful for
navigation or side bars that you want to follow the user.
If we were, for instance, to change the positioning of an image on the page so that it would be located
30px from the left of its original location (the original location is the left margin of the page), we could write:
img {
position: relative;
18
left: 30px;
Changing the position to 30px from the left is essentially the same as changing the left margin of the
image by 30px.
If we were to change the positioning of an image nested inside a div so that it would be located 30px from
the right edge of the div, we would write:
img {
position: absolute;
right: 30px;
This essentially adds a 30px margin between the parent element and the child element.
Centering Elements
You can center elements by applying the text-align property within a parent element (like the body, or the
div). This way of centering only works if you don’t change the default width of a block element.
body {
text-align: center;
An alternative is by using the margin property with value auto which will automatically center an element
either vertically or horizontally. For instance, if we want to center the h1 tags horizontally, we want a zero
margin on the top and bottom, and auto on left and right:
h1 {
width: 10%;
Layout - Flexbox
Introduction
Flexbox stands for ”flexible box”. It’s a display type that comes with many properties that allow for diverse
arrangement of items. It’s an alternative to float: left;, float: right;, display: block; that were covered
in the previous section.
The flexbox element is split into two parts: the container and the items. The container is the parent element
usually in the form of a div. Flex items are child elements of the container and make up the contents of the
box.
19
Creating a Flex container
Suppose, for example, that we have a div element with class container that will act as the container, with
several other div elements inside it like so:
<div class="container>
<div class="container-item>A</div>
<div class="container-item>B</div>
<div class="container-item>C</div>
<div class="container-item>D</div>
<div class="container-item>E</div>
</div>
To set up the flex container, set the display property equal to flex.
.container {
background-color: rgb(250,250,250);
margin: 10px;
display: flex;
We can specify the direction we want the items to go in. Add the property flex-direction. The default
value for this property is row, there’s also the option of column. If you want to go in the reverse direction, add
the suffix reverse as in row-reverse.
.container {
background-color: rgb(250,250,250);
margin: 10px;
display: flex;
flex-direction: row;
The flex-wrap property set to the value wrap makes it so that once the content inside the container reaches
a certain length, the content wraps around. The other options for this property are nowrap (default value) and
wrap-reverse which reverses the order.
.container {
background-color: rgb(250,250,250);
margin: 10px;
display: flex;
flex-direction: row;
flex-wrap: wrap;
20
}
Content Alignment
There are two main properties used to align content inside of flex containers, one responsible for the hor-
izontal alignment and the other for the vertical alignment.
The justify-content is used for horizontal alignment and takes in one of three main values: flex-start,
flex-end, center; these values are used for left justify, right justify and centralization, respectively. There are
also other values: space-between, which makes it so that the items are equally spaced and fill the entire con-
tainer, space-around creates space not only between the items but also around the edges of the container.
.container {
background-color: rgb(250,250,250);
margin: 10px;
height: 300px;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-around;
The aling-items aligns items vertically. By default it has the stretch value. Other options are: center, which
puts items in between the top and the bottom, flex-start, which puts the items at the top, flex-end which
puts the items at the bottom of the container. The final option for the value of this property is baseline which
sets all items to be centered around the same horizontal line; this could be useful when the items differ in their
line-height property.
.container {
background-color: rgb(250,250,250);
margin: 10px;
height: 300px;
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-around;
align-items: baseline;
21
Flex item order
The order property can be used to change the positioning of the items inside a container. This property
can be added directly to the HTML code in the style attribute (otherwise we would have to create a new CSS
style block for each of the items). This property is useful because then we don’t have to manually move the
positioning of the divs. The default value of this property is 0 (keeps it in its location). The following piece of
code will order the items as DEBAC.
<div class="container>
</div>
The flex-basis property defines the minimum width of a flex item. The flex-grow property makes it so that
an item gets more space than the rest of the items; the default value is 0. For instance, the item labeled ”C”
gets five times the normal amount of space given to the other items. This is useful because when the window
of the browser is resized, the items still take up the same amount of space, proportionally.
<div class="container">
flex-basis: 100px;
flex-grow: 1;"
>A</div>
flex-basis: 100px;
flex-grow: 1;"
B</div>
flex-basis: 100px;
flex-grow: 5;"
C</div>
flex-basis: 100px;
flex-grow: 1;"
D</div>
flex-basis: 100px;
22
flex-grow: 1;"
E</div>
</div>
When the width of the items go below the minimum width established by the flex-basis property, the width
of the items are defined by the flex-shrink property. This property defines the rate of shrinkage of each
container item relative to the rest of the items. The default value for this is 1, instead of 0. If you don’t want an
item to shrink, set its value to 0. The following piece of code makes it so that the middle item (letter B) shrinks
3 times faster than the rest of the items.
<div class="container>
flex-basis: 100px;
flex-grow: 1;
flex-shrink: 1;"
>A</div>
flex-basis: 100px;
flex-grow: 1;
flex-shrink: 3;"
B</div>
flex-basis: 100px;
flex-grow: 5;
flex-shrink: 1;"
C</div>
flex-basis: 100px;
flex-grow: 1;
flex-shrink: 1;"
D</div>
flex-basis: 100px;
flex-grow: 1;
flex-shrink: 1;"
E</div>
</div>
23
Flex Property
The flex property allows us to summarize the properties covered in the last section to one simple property.
The flex property takes in three values: grow, shrink and basis separated by a whitespace.
<div class="container>
flex: 1 1 100px;"
>A</div>
flex: 1 3 100px;"
B</div>
flex: 5 1 100px;"
C</div>
flex: 1 1 100px;"
D</div>
flex: 1 1 100px;"
E</div>
</div>
Item alignment
In order to aling items vertically we use the aling-self property, which overwrites the align-items property
if it was set in the parent container (it will only overwrite aling-items if aling-self is applied for a particular
item; the remaining items will take the value defined by aling-items). This property takes in the same values
as the aling-items property except for stretch.
<div class="container>
flex: 1 1 100px;
align-self: center;"
>A</div>
flex: 1 3 100px;
align-self: flex-end;"
B</div>
24
<div class="container-item style="order: 5;>
flex: 5 1 100px;
align-self: flex-start;"
C</div>
flex: 1 1 100px;
aling-self: flex-start;"
D</div>
flex: 1 1 100px;
aling-self: center;"
E</div>
</div>
Layout - Grid
Introduction
Grid is an alternative to the Flexbox and Box models in CSS. The grid system allows for more control of
the container, giving the user more tools. The Grid system is focused on both the width and height whereas
Flexbox is more focused on the width alone.
Creating a Grid
First let’s create a parent div environment with its div items, similar to what was done in the Flexbox section.
<div class="grid-container">
>1</div>
>2</div>
>3</div>
>4</div>
25
background: rgb(140, 210, 255);
>5</div>
</div>
.grid-container {
background-color: rgb(250,250,250);
margin: 10px;
height: 300px;
display: grid;
Unlike Flex, Grid allows us to set the number of rows and columns manually, using grid-template-columns
and grid-template-rows. To set them up, type the size that you want the column/row to be. The amount of val-
ues determines the amount of columns/rows that will be created. If you type 3 values for grid-template-columns,
3 columns with the specified values will be created.
.grid-container {
background-color: rgb(250,250,250);
margin: 10px;
height: 300px;
display: grid;
To keep things consistent between different devices, we can set each of the values equal to auto which will
divide the space evenly no matter the size.
.grid-container {
background-color: rgb(250,250,250);
margin: 10px;
height: 300px;
display: grid;
26
Justify and Align Grid
The justify-content property has three main values: center, start, end (no need to use any prefixes, just
the keywords). The other values are: space-around and space-envely(does the same thing as space-between in
Flexbox).
.grid-container {
background-color: rgb(250,250,250);
margin: 10px;
height: 300px;
display: grid;
justify-content: space-envely;
The align-content property has values: space-between (adds space between the items, but not to the top and
bottom items in relationship to the margin), space-evenly (adds space all around the items, including to the
top and bottom), as well as the three main values: center, start, end.
.grid-container {
background-color: rgb(250,250,250);
margin: 10px;
height: 300px;
display: grid;
justify-content: space-envely;
align-content: end;
The property for introducing gaps between columns is grid-column-gap, that takes in one value. The prop-
erty for introducing gaps between rows is grid-row-gap.
.grid-container {
background-color: rgb(250,250,250);
margin: 10px;
height: 300px;
27
display: grid;
grid-column-gap: 150px;
grid-column-gap: 300px;
Instead of having to specify row or column we can use a shorthand property and specify both with a single
property by passing two values to the grid-gap property. The first value is the row gap and the second value
is the column gap.
.grid-container {
background-color: rgb(250,250,250);
margin: 10px;
height: 300px;
display: grid;
In this section we’ll be customizing sizing of each item in the ”grid container”. Currently, the items look like
this:
<div class="grid-container">
">1</div>
">2</div>
">3</div>
">4</div>
28
">5</div>
">6</div>
</div>
With the grid-column property, specify a start and end point, separated by a forward slash /. For instance, by
doing grid-column: 1/3 for our first item, this item will now start at line 1 and span both line 1 and 2, ending at
line 3. The second item will start at line 3. The same principle applies to the property grid-row.
<div class="grid-container">
grid-column: 1 / 3;
grid-row: 1 / 3;
">1</div>
">2</div>
">3</div>
">4</div>
">5</div>
">6</div>
</div>
Alternatively we can specify the distance that the item is going to take up using the keyword span. Now you
only need to specify the starting point, and the amount of spaces you want that item to take up. The following
piece of code is equivalent to the previous one:
<div class="grid-container">
grid-column: 1 / span 2;
grid-row: 1 / span 2;
">1</div>
29
<div class="grid-item" style="
">2</div>
">3</div>
">4</div>
">5</div>
">6</div>
</div>
Grid Area
There’s a way to specify both the grid row and grid column with a single property, grid-area. The first value
is the row starting point, the next is the column starting point separated by the rows starting point with a /,
followed by row end, and column end.
<div class="grid-container">
">1</div>
">2</div>
">3</div>
">4</div>
">5</div>
30
background: rgb(255, 203, 99);
">6</div>
</div>
Transition Property
The transition property works well with pseudoselectors. We are going to model a submit button, with a
pseudoselector of hover. This is how it looks like:
.submit-button {
border: none;
text-decoration: none;
color: white;
.submit-button:hover {
Now let’s add a transition property to the base .submit-button; this will make it so that there is a smooth
transition between the two states of the button (without and with cursor hovering over it).
• name: the name of the property you want to make a change; in our case it’s the background property.
.submit-button {
border: none;
text-decoration: none;
color: white;
31
transition: background 300ms ease-in-out 0.1s;
.submit-button:hover {
If there are multiple properties you want to change, you have to separate each property with a comma, or
alternatively type all to make all of them change. Let’s make it so that the padding of the text is changed
alongside the color of the background for our submit button.
.submit-button {
border: none;
text-decoration: none;
color: white;
.submit-button:hover {
Many older versions of web browser don’t support this functionality that comes with newer versions of CSS.
So in order to get around that, we need to add a browser support prefix to our transition property. This prefix
will depend on the browser: -webkit- for Chrome and Safari, -moz- for Mozilla Firefox, -o- for Opera, -ms- for
Internet Explorer. Note that we can’t string all of these prefixes together, meaning you’re going to have to
create a new line for each browser you want to support.
Transformation Functions
Transformation functions take in inputs and physically change what is displayed on the page. In order to
apply these functions, we must use the transform property.
The translate() function takes in two values, the first one is the X shift (right shift are represented by
positive numbers and left shift are represented by negative numbers) and the second is the Y shift (upwards
shift are represented by positive numbers and downwards shift are represented by negative numbers).
.submit-button {
32
padding: 10px 15px;
border: none;
text-decoration: none;
color: white;
The scale() function takes in a value to increase the size of the item it applies to.
.submit-button {
border: none;
text-decoration: none;
color: white;
transform: scale(2.5);
The rotate() function takes in one value in degrees. This will rotate the item around its center.
.submit-button {
border: none;
text-decoration: none;
color: white;
transform: rotate(-90deg);
The next two functions we’re going to cover skew the item along a certain axis. The skewX() function rotates
it around the X axis, and takes in a value in degrees. The skewY() function rotatas it around the Y axis.
.submit-button {
border: none;
text-decoration: none;
color: white;
33
background: rgb(89, 150, 255);
transform: skewX(-45deg);
The matrix() function summarizes all of the above functions. This takes in 6 arguments (but it doesn’t work
with rotation, only with skew). The order of the arguments is: X scale (default 1), skewY (default 0), skewX
(default 0), Y scale (default 1), translate X and translate Y. There’s no need to include any units.
.submit-button {
border: none;
text-decoration: none;
color: white;
With an animation we can define all the changes we want to make once and then apply it to any item we
want instead of having to manually set the transitions to each individual item. With animations, we can also
play them at the start, when the page is first loaded, instead of having to wait for some event to happen with
a pseudoselector.
Each animation has at least 2 parts (a start and an ending) and we can add more. To create an animation,
use @keyframes followed by the name of the animation. The animation is initialized using the keyword from
followed by curly braces and is ended using the keyword to also followed by curly braces. The convention is
to keep the curly braces in the same line but if the line is getting too large, you can move them over to the
next line.
To create an animation that changes the background color from red to black, we’d write:
@keyframes red-to-black {
to {background: black;}
Another way to do this is by using percentages, where 0% represents the beginning of the animation and 100%
represents the ending of the animation. The advantage of doing this is that we can add additional steps.
@keyframes red-to-black {
34
0% {background: red;}
@keyframes red-to-black {
0% {background: red;}
We can also work with multiple properties. Below, the transform property was added, alongside the back-
ground color.
@keyframes red-to-black {
Adding an animation
In this section we’re going to add an animation to an element. We’re going to apply our animation to some
text on the page:
Then use the property animation-name and reference the name of the animation.
#about-me {
animation-name: red-to-black;
Next, we need to add some animation properties to see the animation work.
Animation properties
The animation-duration property allows the animation to run; the default value of this property is 0. Set a
different value in seconds.
#about-me {
animation-name: red-to-black;
animation-duration: 4s;
35
The animation-timing-function property defines how the animation plays out in terms of speed. The main
options are: ease, linear, ease-in-out.
#about-me {
animation-name: red-to-black;
animation-duration: 4s;
animation-timing-function: linear;
The animation-delay is the amount of time it takes for the animation to start; it can take in positive or negative
values. The default value is 0; the animation starts when the page loads.
#about-me {
animation-name: red-to-black;
animation-duration: 4s;
animation-timing-function: linear;
animation-delay: 2s;
The animation-iteration-count is the number of times the animation repeats itself. It can take in a numerical
value or the special value infinite.
#about-me {
animation-name: red-to-black;
animation-duration: 4s;
animation-timing-function: linear;
animation-delay: 2s;
animation-iteration-count: infinite;
The animation-direction property has the following main values: normal (animation goes from 0% to 100%),
reverse (animation goes from 100% to 0%, alternate (animation goes from 0 to 100% and then from 100% to
0%), alternate-reverse (same as alternate but starts at 100% instead of 0%).
#about-me {
animation-name: red-to-black;
animation-duration: 4s;
animation-timing-function: linear;
animation-delay: 2s;
animation-iteration-count: infinite;
animation-direction: reverse;
You can use the animation property as a shorthand to summarize all of these properties at once. This property
takes 5 values: animation name, duration, timing, delay, iteration and direction. This makes it easier to add the
36
browser prefixes.
#about-me {
Responsive Websites
Introduction
Making a website that looks good both on mobile and desktop is important since the majority of internet
users browse the web on their mobile phones. Having a mobile-unfriendly website will penalize you because
your website will rank poorly on search indexes.
To test whether your website is mobile-friendly, type its URL inside the text box of Mobile-Friendly Test.
One way to solve the issue is by creating a separate website specifically tailored for mobile users. Many
websites such as Facebook do this. If you try to access facebook.com when on mobile, you are automatically
redirected to m.facebook.com.
An alternative solution is to add responsiveness to your website; that way you avoid having to design two
different websites.
Important Terminology
• Browser Size: can be changed by dragging the browser window from left to right or vice-versa.
With CSS Media Query, only if a certain statement is true the code (styling options) are applied. The syntax
starts with the @media keyword, followed by <type> which specifies the type of media query (e.g. code only
to be executed if the website is being displayed in a small screen, or if it’s on a screen reader, or if it’s being
printed etc.), followed by the <feature>. Finally, we have a block of CSS code that will be executed when the
query is true.
It’s also possible to combine different features. If we want to make change the display of text to red, for
screens with a width greater than 900px but less than 1000px:
h1 {
37
color: red;
In the example above, screen represents the <type> of query, and min-width represents the <feature>.
If we want to make the h1 text of a web page red only when the page is being printed:
@media print {
h1 {
color: red;
38