CSS Introduction (#1)
CSS is the language we use to style a Web page.
What is CSS?
- CSS stands for Cascading Style Sheets
- CSS describes how HTML elements are to be displayed on screen, paper, or in other media
- CSS saves a lot of work. It can control the layout of multiple web pages all at once
- External stylesheets are stored in CSS files
CSS Demo – One HTML Page – Multiple Styles!
Here we will show one HTML page displayed with four different stylesheets.
Why Use CSS?
CSS is used to define styles for your web pages, including the design, layout and variations in display for different devices and screen sizes.
CSS Example
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
p {
font-family: verdana;
font-size: 20px;
}
CSS Solved a Big Problem
HTML was NEVER intended to contain tags for formatting a web page!
HTML was created to describe the content of a web page, like:
<h1>This is a heading</h1> <p>This is a paragraph.</p>
When tags like <font>, and color attributes were added to the HTML 3.2 specification, it started a nightmare for web developers. Development of large websites, where fonts and color information were added to every single page, became a long and expensive process.
To solve this problem, the World Wide Web Consortium (Swift Games) created CSS.
CSS removed the style formatting from the HTML page!
If you don’t know what HTML is, we suggest that you read our HTML Tutorial.
CSS Saves a Lot of Work!
The style definitions are normally saved in external .css files.
With an external stylesheet file, you can change the look of an entire website by changing just one file!
CSS Syntax (#2)
A CSS rule consists of a selector and a declaration block.
CSS Syntax
The selector points to the HTML element you want to style.
The declaration block contains one or more declarations separated by semicolons.
Each declaration includes a CSS property name and a value, separated by a colon.
Multiple CSS declarations are separated with semicolons, and declaration blocks are surrounded by curly braces.
Example
In this example all <p> elements will be center-aligned, with a red text color:
p {
color: red;
text-align: center;
}
Example Explained
p
is a selector in CSS (it points to the HTML element you want to style: <p>).color
is a property, andred
is the property valuetext-align
is a property, andcenter
is the property value
CSS Selectors (#3)
A CSS selector selects the HTML element(s) you want to style.
CSS Selectors
CSS selectors are used to “find” (or select) the HTML elements you want to style.
We can divide CSS selectors into five categories:
- Simple selectors (select elements based on name, id, class)
- Combinator selectors (select elements based on a specific relationship between them)
- Pseudo-class selectors (select elements based on a certain state)
- Pseudo-elements selectors (select and style a part of an element)
- Attribute selectors (select elements based on an attribute or attribute value)
This page will explain the most basic CSS selectors.
The CSS element Selector
The element selector selects HTML elements based on the element name.
Example
Here, all <p> elements on the page will be center-aligned, with a red text color:
p {
text-align: center;
color: red;
}
The CSS id Selector
The id selector uses the id attribute of an HTML element to select a specific element.
The id of an element is unique within a page, so the id selector is used to select one unique element!
To select an element with a specific id, write a hash (#) character, followed by the id of the element.
Example
The CSS rule below will be applied to the HTML element with id=”para1″:
#para1 {
text-align: center;
color: red;
}
Note: An id name cannot start with a number!
The CSS class Selector
The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the class name.
Example
In this example all HTML elements with class=”center” will be red and center-aligned:
.center {
text-align: center;
color: red;
}
You can also specify that only specific HTML elements should be affected by a class.
Example
In this example only <p> elements with class=”center” will be red and center-aligned:
p.center {
text-align: center;
color: red;
}
HTML elements can also refer to more than one class.
Example
In this example the <p> element will be styled according to class=”center” and to class=”large”:
<p class="center large">This paragraph refers to two classes.</p>
Note: A class name cannot start with a number!
The CSS Universal Selector
The universal selector (*) selects all HTML elements on the page.
Example
The CSS rule below will affect every HTML element on the page:
* {
text-align: center;
color: blue;
}
The CSS Grouping Selector
The grouping selector selects all the HTML elements with the same style definitions.
Look at the following CSS code (the h1, h2, and p elements have the same style definitions):
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
p {
text-align: center;
color: red;
}
It will be better to group the selectors, to minimize the code.
To group selectors, separate each selector with a comma.
Example
In this example we have grouped the selectors from the code above:
h1, h2, p {
text-align: center;
color: red;
}
How To Add CSS (#4)
When a browser reads a style sheet, it will format the HTML document according to the information in the style sheet.
Three Ways to Insert CSS
There are three ways of inserting a style sheet:
- External CSS
- Internal CSS
- Inline CSS
External CSS
With an external style sheet, you can change the look of an entire website by changing just one file!
Each HTML page must include a reference to the external style sheet file inside the <link> element, inside the head section.
Example
External styles are defined within the <link> element, inside the <head> section of an HTML page:
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="mystyle.css"> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> </body> </html>
An external style sheet can be written in any text editor, and must be saved with a .css extension.
The external .css file should not contain any HTML tags.
Here is how the “mystyle.css” file looks:
“mystyle.css”
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
Note: Do not add a space between the property value and the unit:
Incorrect (space): margin-left: 20 px;
Correct (nospace): margin-left: 20px;
Internal CSS
An internal style sheet may be used if one single HTML page has a unique style.
The internal style is defined inside the <style> element, inside the head section.
Example
Internal styles are defined within the <style> element, inside the <head> section of an HTML page:
<!DOCTYPE html> <html> <head> <style> body { background-color: linen; } h1 { color: maroon; margin-left: 40px; } </style> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> </body> </html>
Inline CSS
An inline style may be used to apply a unique style for a single element.
To use inline styles, add the style attribute to the relevant element. The style attribute can contain any CSS property.
Example
Inline styles are defined within the “style” attribute of the relevant element:
<!DOCTYPE html> <html> <body> <h1 style="color:blue;text-align:center;">This is a heading</h1> <p style="color:red;">This is a paragraph.</p> </body> </html>
Tip: An inline style loses many of the advantages of a style sheet (by mixing content with presentation). Use this method sparingly.
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.
Assume that an external style sheet has the following style for the <h1> element:
h1 {
color: navy;
}
Then, assume that an internal style sheet also has the following style for the <h1> element:
h1 {
color: orange;
}
Example
If the internal style is defined after the link to the external style sheet, the <h1> elements will be “orange”:
<head> <link rel="stylesheet" type="text/css" href="mystyle.css"> <style> h1 { color: orange; } </style> </head>
Example
However, if the internal style is defined before the link to the external style sheet, the <h1> elements will be “navy”:
<head> <style> h1 { color: orange; } </style> <link rel="stylesheet" type="text/css" href="mystyle.css"> </head>
Cascading Order
What style will be used when there is more than one style specified for an HTML element?
All the styles in a page will “cascade” into a new “virtual” style sheet by the following rules, where number one has the highest priority:
- Inline style (inside an HTML element)
- External and internal style sheets (in the head section)
- Browser default
So, an inline style has the highest priority, and will override external and internal styles and browser defaults.
CSS Comments (#5)
CSS comments are not displayed in the browser, but they can help document your source code.
CSS Comments
Comments are used to explain the code, and may help when you edit the source code at a later date.
Comments are ignored by browsers.
A CSS comment is placed inside the <style>
element, and starts with /*
and ends with */
:
Example
/* This is a single-line comment */
p {
color: red;
}
You can add comments wherever you want in the code:
Example
p {
color: red; /* Set text color to red */
}
Comments can also span multiple lines:
Example
/* This is
a multi-line
comment */
p {
color: red;
}
HTML and CSS Comments
From the HTML tutorial, you learned that you can add comments to your HTML source by using the <!--...-->
syntax.
In the following example, we use a combination of HTML and CSS comments:
Example
<!DOCTYPE html> <html> <head> <style> p { color: red; /* Set text color to red */ } </style> </head> <body> <h2>My Heading</h2> <!-- These paragraphs will be red --> <p>Hello World!</p> <p>This paragraph is styled with CSS.</p> <p>CSS comments are not shown in the output.</p> </body> </html>
CSS Backgrounds (#6)
The CSS background properties are used to add background effects for elements.
In these chapters, you will learn about the following CSS background properties:
background-color
background-image
background-repeat
background-attachment
background-position
background
(shorthand property)
CSS background-color
The background-color
property specifies the background color of an element.
Example
The background color of a page is set like this:
body {
background-color: lightblue;
}
With CSS, a color is most often specified by:
- a valid color name – like “red”
- a HEX value – like “#ff0000”
- an RGB value – like “rgb(255,0,0)”
Other Elements
You can set the background color for any HTML elements:
Example
Here, the <h1>, <p>, and <div> elements will have different background colors:
h1 {
background-color: green;
}
div {
background-color: lightblue;
}
p {
background-color: yellow;
}
Opacity / Transparency
The opacity
property specifies the opacity/transparency of an element. It can take a value from 0.0 – 1.0. The lower value, the more transparent:
opacity 1
opacity 0.6
opacity 0.3
opacity 0.1
Example
div {
background-color: green;
opacity: 0.3;
}
Note: When using the opacity
property to add transparency to the background of an element, all of its child elements inherit the same transparency. This can make the text inside a fully transparent element hard to read.
Transparency using RGBA
If you do not want to apply opacity to child elements, like in our example above, use RGBA color values. The following example sets the opacity for the background color and not the text:
100% opacity
60% opacity
30% opacity
10% opacity
An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).
Example
div {
background: rgba(0, 128, 0, 0.3) /* Green background with 30% opacity */
}
CSS Background Image (#7)
CSS background-image
The background-image
property specifies an image to use as the background of an element.
By default, the image is repeated so it covers the entire element.
Example
Set the background image for a page:
body {
background-image: url("paper.gif");
}
Example
This example shows a bad combination of text and background image. The text is hardly readable:
body {
background-image: url("bgdesert.jpg");
}
Note: When using a background image, use an image that does not disturb the text.
The background image can also be set for specific elements, like the <p> element:
Example
p {
background-image: url("paper.gif");
}
CSS Background Image Repeat (#8)
CSS background-repeat
By default, the background-image
property repeats an image both horizontally and vertically.
Some images should be repeated only horizontally or vertically, or they will look strange, like this:
Example
body {
background-image: url("gradient_bg.png");
}
If the image above is repeated only horizontally (background-repeat: repeat-x;
), the background will look better:
Example
body {
background-image: url("gradient_bg.png");
background-repeat: repeat-x;
}
Tip: To repeat an image vertically, set background-repeat: repeat-y;
CSS background-repeat: no-repeat
Showing the background image only once is also specified by the background-repeat
property:
Example
Show the background image only once:
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
}
In the example above, the background image is placed in the same place as the text. We want to change the position of the image, so that it does not disturb the text too much.
CSS background-position
The background-position
property is used to specify the position of the background image.
Example
Position the background image in the top-right corner:
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}
CSS Background Attachment (#9)
CSS background-attachment
The background-attachment
property specifies whether the background image should scroll or be fixed (will not scroll with the rest of the page):
Example
Specify that the background image should be fixed:
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: fixed;
}
Example
Specify that the background image should scroll with the rest of the page:
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: scroll;
}
CSS Background Shorthand (#10)
CSS background – Shorthand property
To shorten the code, it is also possible to specify all the background properties in one single property. This is called a shorthand property.
Instead of writing:
body {
background-color: #ffffff;
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}
You can use the shorthand property background
:
Example
Use the shorthand property to set the background properties in one declaration:
body {
background: #ffffff url("img_tree.png") no-repeat right top;
}
When using the shorthand property the order of the property values is:
background-color
background-image
background-repeat
background-attachment
background-position
It does not matter if one of the property values is missing, as long as the other ones are in this order. Note that we do not use the background-attachment property in the examples above, as it does not have a value.
CSS Borders (#11)
The CSS border properties allow you to specify the style, width, and color of an element’s border.
I have borders on all sides.
I have a red bottom border.
I have rounded borders.
CSS Border Style
The border-style
property specifies what kind of border to display.
The following values are allowed:
dotted
– Defines a dotted borderdashed
– Defines a dashed bordersolid
– Defines a solid borderdouble
– Defines a double bordergroove
– Defines a 3D grooved border. The effect depends on the border-color valueridge
– Defines a 3D ridged border. The effect depends on the border-color valueinset
– Defines a 3D inset border. The effect depends on the border-color valueoutset
– Defines a 3D outset border. The effect depends on the border-color valuenone
– Defines no borderhidden
– Defines a hidden border
The border-style
property can have from one to four values (for the top border, right border, bottom border, and the left border).
Example
Demonstration of the different border styles:
p.dotted {border-style: dotted;}
p.dashed {border-style: dashed;}
p.solid {border-style: solid;}
p.double {border-style: double;}
p.groove {border-style: groove;}
p.ridge {border-style: ridge;}
p.inset {border-style: inset;}
p.outset {border-style: outset;}
p.none {border-style: none;}
p.hidden {border-style: hidden;}
p.mix {border-style: dotted dashed solid double;}
Result:
A dotted border.
A dashed border.
A solid border.
A double border.
A groove border. The effect depends on the border-color value.
A ridge border. The effect depends on the border-color value.
An inset border. The effect depends on the border-color value.
An outset border. The effect depends on the border-color value.
No border.
A hidden border.
A mixed border.
CSS Border Width (#12)
The border-width
property specifies the width of the four borders.
The width can be set as a specific size (in px, pt, cm, em, etc) or by using one of the three pre-defined values: thin, medium, or thick:
Example
Demonstration of the different border widths:
p.one {
border-style: solid;
border-width: 5px;
}
p.two {
border-style: solid;
border-width: medium;
}
p.three {
border-style: dotted;
border-width: 2px;
}
p.four {
border-style: dotted;
border-width: thick;
}
Result:
Specific Side Widths
The border-width
property can have from one to four values (for the top border, right border, bottom border, and the left border):
Example
p.one {
border-style: solid;
border-width: 5px 20px; /* 5px top and bottom, 20px on the sides */
}
p.two {
border-style: solid;
border-width: 20px 5px; /* 20px top and bottom, 5px on the sides */
}
p.three {
border-style: solid;
border-width: 25px 10px 4px 35px; /* 25px top, 10px right, 4px bottom and 35px left */
}
CSS Border – Individual Sides (#13)
From the examples on the previous pages, you have seen that it is possible to specify a different border for each side.
In CSS, there are also properties for specifying each of the borders (top, right, bottom, and left):
Example
p {
border-top-style: dotted;
border-right-style: solid;
border-bottom-style: dotted;
border-left-style: solid;
}
Result:
The example above gives the same result as this:
Example
p {
border-style: dotted solid;
}
So, here is how it works:
If the border-style
property has four values:
- border-style: dotted solid double dashed;
- top border is dotted
- right border is solid
- bottom border is double
- left border is dashed
If the border-style
property has three values:
- border-style: dotted solid double;
- top border is dotted
- right and left borders are solid
- bottom border is double
If the border-style
property has two values:
- border-style: dotted solid;
- top and bottom borders are dotted
- right and left borders are solid
If the border-style
property has one value:
- border-style: dotted;
- all four borders are dotted
Example
/* Four values */
p {
border-style: dotted solid double dashed;
}
/* Three values */
p {
border-style: dotted solid double;
}
/* Two values */
p {
border-style: dotted solid;
}
/* One value */
p {
border-style: dotted;
}
The border-style
property is used in the example above. However, it also works with border-width
and border-color
.
CSS Border – Shorthand Property
Like you saw in the previous page, there are many properties to consider when dealing with borders.
To shorten the code, it is also possible to specify all the individual border properties in one property.
The border
property is a shorthand property for the following individual border properties:
border-width
border-style
(required)border-color
Example
p {
border: 5px solid red;
}
Result:
Some text
You can also specify all the individual border properties for just one side:
Left Border
p {
border-left: 6px solid red;
}
Result:
Some text
Bottom Border
p {
border-bottom: 6px solid red;
}
Result:
Some text
CSS Rounded Borders
The border-radius
property is used to add rounded borders to an element:
Normal border
Round border
Rounder border
Roundest border
Example
p {
border: 2px solid red;
border-radius: 5px;
}
More Examples
All the top border properties in one declaration
This example demonstrates a shorthand property for setting all of the properties for the top border in one declaration.
Set the style of the bottom border
This example demonstrates how to set the style of the bottom border.
Set the width of the left border
This example demonstrates how to set the width of the left border.
Set the color of the four borders
This example demonstrates how to set the color of the four borders. It can have from one to four colors.
Set the color of the right border
This example demonstrates how to set the color of the right border.
CSS Padding (#14)
Padding is used to create space around an element’s content, inside of any defined borders.
CSS Padding
The CSS padding
properties are used to generate space around an element’s content, inside of any defined borders.
With CSS, you have full control over the padding. There are properties for setting the padding for each side of an element (top, right, bottom, and left).
Padding – Individual Sides
CSS has properties for specifying the padding for each side of an element:
padding-top
padding-right
padding-bottom
padding-left
All the padding properties can have the following values:
- length – specifies a padding in px, pt, cm, etc.
- % – specifies a padding in % of the width of the containing element
- inherit – specifies that the padding should be inherited from the parent element
Note: Negative values are not allowed.
Example
Set different padding for all four sides of a <div> element:
div {
padding-top: 50px;
padding-right: 30px;
padding-bottom: 50px;
padding-left: 80px;
}
Padding – Shorthand Property
To shorten the code, it is possible to specify all the padding properties in one property.
The padding
property is a shorthand property for the following individual padding properties:
padding-top
padding-right
padding-bottom
padding-left
So, here is how it works:
If the padding
property has four values:
- padding: 25px 50px 75px 100px;
- top padding is 25px
- right padding is 50px
- bottom padding is 75px
- left padding is 100px
Example
Use the padding shorthand property with four values:
div {
padding: 25px 50px 75px 100px;
}
If the padding
property has three values:
- padding: 25px 50px 75px;
- top padding is 25px
- right and left paddings are 50px
- bottom padding is 75px
Example
Use the padding shorthand property with three values:
div {
padding: 25px 50px 75px;
}
If the padding
property has two values:
- padding: 25px 50px;
- top and bottom paddings are 25px
- right and left paddings are 50px
Example
Use the padding shorthand property with two values:
div {
padding: 25px 50px;
}
If the padding
property has one value:
- padding: 25px;
- all four paddings are 25px
Example
Use the padding shorthand property with one value:
div {
padding: 25px;
}
Padding and Element Width
The CSS width
property specifies the width of the element’s content area. The content area is the portion inside the padding, border, and margin of an element.
So, if an element has a specified width, the padding added to that element will be added to the total width of the element. This is often an undesirable result.
Example
Here, the <div> element is given a width of 300px. However, the actual width of the <div> element will be 350px (300px + 25px of left padding + 25px of right padding):
div {
width: 300px;
padding: 25px;
}
To keep the width at 300px, no matter the amount of padding, you can use the box-sizing
property. This causes the element to maintain its actual width; if you increase the padding, the available content space will decrease.
Example
Use the box-sizing property to keep the width at 300px, no matter the amount of padding:
div {
width: 300px;
padding: 25px;
box-sizing: border-box;
}
CSS Height, Width and Max-width (#15)
The CSS height
and width
properties are used to set the height and width of an element.
The CSS max-width
property is used to set the maximum width of an element.
CSS Setting height and width
The height
and width
properties are used to set the height and width of an element.
The height and width properties do not include padding, borders, or margins. It sets the height/width of the area inside the padding, border, and margin of the element.
CSS height and width Values
The height
and width
properties may have the following values:
auto
– This is default. The browser calculates the height and widthlength
– Defines the height/width in px, cm etc.%
– Defines the height/width in percent of the containing blockinitial
– Sets the height/width to its default valueinherit
– The height/width will be inherited from its parent value
CSS height and width Examples
Example
Set the height and width of a <div> element:
div {
height: 200px;
width: 50%;
background-color: powderblue;
}
Example
Set the height and width of another <div> element:
div {
height: 100px;
width: 500px;
background-color: powderblue;
}
Note: Remember that the height
and width
properties do not include padding, borders, or margins! They set the height/width of the area inside the padding, border, and margin of the element!
Setting max-width
The max-width
property is used to set the maximum width of an element.
The max-width
can be specified in length values, like px, cm, etc., or in percent (%) of the containing block, or set to none (this is default. Means that there is no maximum width).
The problem with the <div>
above occurs when the browser window is smaller than the width of the element (500px). The browser then adds a horizontal scrollbar to the page.
Using max-width
instead, in this situation, will improve the browser’s handling of small windows.
Tip: Drag the browser window to smaller than 500px wide, to see the difference between the two divs!
Note: If you for some reason use both the width
property and the max-width
property on the same element, and the value of the width
property is larger than the max-width
property; the max-width
property will be used (and the width
property will be ignored).
Example
This <div> element has a height of 100 pixels and a max-width of 500 pixels:
div {
max-width: 500px;
height: 100px;
background-color: powderblue;
}
CSS Box Model (#16)
All HTML elements can be considered as boxes.
The CSS Box Model
In CSS, the term “box model” is used when talking about design and layout.
The CSS box model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content. The image below illustrates the box model:
Explanation of the different parts:
- Content – The content of the box, where text and images appear
- Padding – Clears an area around the content. The padding is transparent
- Border – A border that goes around the padding and content
- Margin – Clears an area outside the border. The margin is transparent
The box model allows us to add a border around elements, and to define space between elements.
Example
Demonstration of the box model:
div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
Width and Height of an Element
In order to set the width and height of an element correctly in all browsers, you need to know how the box model works.
Important: When you set the width and height properties of an element with CSS, you just set the width and height of the content area. To calculate the full size of an element, you must also add padding, borders and margins.
Example
This <div> element will have a total width of 350px:
div {
width: 320px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}
Here is the calculation:
The total width of an element should be calculated like this:
Total element width = width + left padding + right padding + left border + right border + left margin + right margin
The total height of an element should be calculated like this:
Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin
CSS Outline (#17)
An outline is a line drawn outside the element’s border.
CSS Outline
An outline is a line that is drawn around elements, OUTSIDE the borders, to make the element “stand out”.
CSS has the following outline properties:
outline-style
outline-color
outline-width
outline-offset
outline
Note: Outline differs from borders! Unlike border, the outline is drawn outside the element’s border, and may overlap other content. Also, the outline is NOT a part of the element’s dimensions; the element’s total width and height is not affected by the width of the outline.
CSS Outline Style
The outline-style
property specifies the style of the outline, and can have one of the following values:
dotted
– Defines a dotted outlinedashed
– Defines a dashed outlinesolid
– Defines a solid outlinedouble
– Defines a double outlinegroove
– Defines a 3D grooved outlineridge
– Defines a 3D ridged outlineinset
– Defines a 3D inset outlineoutset
– Defines a 3D outset outlinenone
– Defines no outlinehidden
– Defines a hidden outline
The following example shows the different outline-style
values:
Example
Demonstration of the different outline styles:
p.dotted {outline-style: dotted;}
p.dashed {outline-style: dashed;}
p.solid {outline-style: solid;}
p.double {outline-style: double;}
p.groove {outline-style: groove;}
p.ridge {outline-style: ridge;}
p.inset {outline-style: inset;}
p.outset {outline-style: outset;}
Result:
A dotted outline.
A dashed outline.
A solid outline.
A double outline.
A groove outline. The effect depends on the outline-color value.
A ridge outline. The effect depends on the outline-color value.
An inset outline. The effect depends on the outline-color value.
An outset outline. The effect depends on the outline-color value.
CSS Text (#18)
CSS has a lot of properties for formatting text.
TEXT FORMATTING
This text is styled with some of the text formatting properties. The heading uses the text-align, text-transform, and color properties. The paragraph is indented, aligned, and the space between characters is specified.
Text Color
The color
property is used to set the color of the text. The color is specified by:
- a color name – like “red”
- a HEX value – like “#ff0000”
- an RGB value – like “rgb(255,0,0)”
The default text color for a page is defined in the body selector.
Example
body {
color: blue;
}
h1 {
color: green;
}
Text Color and Background Color
In this example, we define both the background-color
property and the color
property:
Example
body {
background-color: lightgrey;
color: blue;
}
h1 {
background-color: black;
color: white;
}
div {
background-color: blue;
color: white;
}
Important: High contrast is very important for people with vision problems. So, always ensure that the contrast between the text color and the background color (or background image) is good!
CSS Text Alignment and Text Direction
In this chapter you will learn about the following properties:
text-align
text-align-last
direction
unicode-bidi
vertical-align
Text Alignment
The text-align
property is used to set the horizontal alignment of a text.
A text can be left or right aligned, centered, or justified.
The following example shows center aligned, and left and right aligned text (left alignment is default if text direction is left-to-right, and right alignment is default if text direction is right-to-left):
Example
h1 {
text-align: center;
}
h2 {
text-align: left;
}
h3 {
text-align: right;
}
When the text-align
property is set to “justify”, each line is stretched so that every line has equal width, and the left and right margins are straight (like in magazines and newspapers):
Example
div {
text-align: justify;
}
Text Align Last
The text-align-last
property specifies how to align the last line of a text.
Example
Align the last line of text in three <p> elements:
p.a {
text-align-last: right;
}
p.b {
text-align-last: center;
}
p.c {
text-align-last: justify;
}
Text Direction
The direction
and unicode-bidi
properties can be used to change the text direction of an element:
Example
p {
direction: rtl;
unicode-bidi: bidi-override;
}
Vertical Alignment
The vertical-align
property sets the vertical alignment of an element.
Example
Set the vertical alignment of an image in a text:
img.a {
vertical-align: baseline;
}
img.b {
vertical-align: text-top;
}
img.c {
vertical-align: text-bottom;
}
img.d {
vertical-align: sub;
}
img.e {
vertical-align: super;
}
CSS Text Shadow (#19)
Text Shadow
The text-shadow
property adds shadow to text.
In its simplest use, you only specify the horizontal shadow (2px) and the vertical shadow (2px):
Text shadow effect!
Example
h1 {
text-shadow: 2px 2px;
}
Next, add a color (red) to the shadow:
Text shadow effect!
Example
h1 {
text-shadow: 2px 2px red;
}
Then, add a blur effect (5px) to the shadow:
Text shadow effect!
Example
h1 {
text-shadow: 2px 2px 5px red;
}
More Text Shadow Examples
Example 1
Text-shadow on a white text:
h1 {
color: white;
text-shadow: 2px 2px 4px #000000;
}
Example 2
Text-shadow with red neon glow:
h1 {
text-shadow: 0 0 3px #ff0000;
}
Example 3
Text-shadow with red and blue neon glow:
h1 {
text-shadow: 0 0 3px #ff0000, 0 0 5px #0000ff;
}
Example 4
h1 {
color: white;
text-shadow: 1px 1px 2px black, 0 0 25px blue, 0 0 5px darkblue;
}
CSS Fonts (#20)
Choosing the right font for your website is important!
Font Selection is Important
Choosing the right font has a huge impact on how the readers experience a website.
The right font can create a strong identity for your brand.
Using a font that is easy to read is important. The font adds value to your text. It is also important to choose the correct color and text size for the font.
Generic Font Families
In CSS there are five generic font families:
- Serif fonts have a small stroke at the edges of each letter. They create a sense of formality and elegance.
- Sans-serif fonts have clean lines (no small strokes attached). They create a modern and minimalistic look.
- Monospace fonts – here all the letters have the same fixed width. They create a mechanical look.
- Cursive fonts imitate human handwriting.
- Fantasy fonts are decorative/playful fonts.
All the different font names belong to one of the generic font families.
Difference Between Serif and Sans-serif Fonts
Note: On computer screens, sans-serif fonts are considered easier to read than serif fonts.
Some Font Examples
Generic Font Family | Examples of Font Names |
---|---|
Serif | Times New Roman Georgia Garamond |
Sans-serif | Arial Verdana Helvetica |
Monospace | Courier New Lucida Console Monaco |
Cursive | Brush Script MT Lucida Handwriting |
Fantasy | Copperplate Papyrus |
The CSS font-family Property
In CSS, we use the font-family
property to specify the font of a text.
Note: If the font name is more than one word, it must be in quotation marks, like: “Times New Roman”.
Tip: The font-family
property should hold several font names as a “fallback” system, to ensure maximum compatibility between browsers/operating systems. Start with the font you want, and end with a generic family (to let the browser pick a similar font in the generic family, if no other fonts are available). The font names should be separated with comma.
Example
Specify some different fonts for three paragraphs:
.p1 {
font-family: "Times New Roman", Times, serif;
}
.p2 {
font-family: Arial, Helvetica, sans-serif;
}
.p3 {
font-family: "Lucida Console", "Courier New", monospace;
}
CSS Icons (#21)
Icons can easily be added to your HTML page, by using an icon library.
How To Add Icons
The simplest way to add an icon to your HTML page, is with an icon library, such as Font Awesome.
Add the name of the specified icon class to any inline HTML element (like <i>
or <span>
).
All the icons in the icon libraries below, are scalable vectors that can be customized with CSS (size, color, shadow, etc.)
Font Awesome Icons
To use the Font Awesome icons, go to fontawesome.com, sign in, and get a code to add in the <head>
section of your HTML page:
<script src="https://kit.fontawesome.com/yourcode.js" crossorigin="anonymous"></script>
Note: No downloading or installation is required!
Example
<!DOCTYPE html> <html> <head> <script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script> </head> <body> <i class="fas fa-cloud"></i> <i class="fas fa-heart"></i> <i class="fas fa-car"></i> <i class="fas fa-file"></i> <i class="fas fa-bars"></i> </body> </html>
Bootstrap Icons
To use the Bootstrap glyphicons, add the following line inside the <head>
section of your HTML page:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
Note: No downloading or installation is required!
Example
<!DOCTYPE html>
<html>
<head>
<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css”>
</head>
<body><i class=”glyphicon glyphicon-cloud”></i>
<i class=”glyphicon glyphicon-remove”></i>
<i class=”glyphicon glyphicon-user”></i>
<i class=”glyphicon glyphicon-envelope”></i>
<i class=”glyphicon glyphicon-thumbs-up”></i>
</body>
</html>
Result:
Google Icons
To use the Google icons, add the following line inside the <head>
section of your HTML page:
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
Note: No downloading or installation is required!
Example
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> </head> <body> <i class="material-icons">cloud</i> <i class="material-icons">favorite</i> <i class="material-icons">attachment</i> <i class="material-icons">computer</i> <i class="material-icons">traffic</i> </body> </html>
CSS Links (#22)
With CSS, links can be styled in many different ways.
Text Link Text Link Link Button Link Button
Styling Links
Links can be styled with any CSS property (e.g. color
, font-family
, background
, etc.).
Example
a {
color: hotpink;
}
In addition, links can be styled differently depending on what state they are in.
The four links states are:
a:link
– a normal, unvisited linka:visited
– a link the user has visiteda:hover
– a link when the user mouses over ita:active
– a link the moment it is clicked
Example
/* unvisited link */
a:link {
color: red;
}
/* visited link */
a:visited {
color: green;
}
/* mouse over link */
a:hover {
color: hotpink;
}
/* selected link */
a:active {
color: blue;
}
When setting the style for several link states, there are some order rules:
- a:hover MUST come after a:link and a:visited
- a:active MUST come after a:hover
Text Decoration
The text-decoration
property is mostly used to remove underlines from links:
Example
a:link {
text-decoration: none;
}
a:visited {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
a:active {
text-decoration: underline;
}
Background Color
The background-color
property can be used to specify a background color for links:
Example
a:link {
background-color: yellow;
}
a:visited {
background-color: cyan;
}
a:hover {
background-color: lightgreen;
}
a:active {
background-color: hotpink;
}
Link Buttons
This example demonstrates a more advanced example where we combine several CSS properties to display links as boxes/buttons:
Example
a:link, a:visited {
background-color: #f44336;
color: white;
padding: 14px 25px;
text-align: center;
text-decoration: none;
display: inline-block;
}
a:hover, a:active {
background-color: red;
}
More Examples
Example
This example demonstrates how to add other styles to hyperlinks:
a.one:link {color: #ff0000;}
a.one:visited {color: #0000ff;}
a.one:hover {color: #ffcc00;}
a.two:link {color: #ff0000;}
a.two:visited {color: #0000ff;}
a.two:hover {font-size: 150%;}
a.three:link {color: #ff0000;}
a.three:visited {color: #0000ff;}
a.three:hover {background: #66ff66;}
a.four:link {color: #ff0000;}
a.four:visited {color: #0000ff;}
a.four:hover {font-family: monospace;}
a.five:link {color: #ff0000; text-decoration: none;}
a.five:visited {color: #0000ff; text-decoration: none;}
a.five:hover {text-decoration: underline;}
Example
Another example of how to create link boxes/buttons:
a:link, a:visited {
background-color: white;
color: black;
border: 2px solid green;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
}
a:hover, a:active {
background-color: green;
color: white;
}
Example
This example demonstrates the different types of cursors (can be useful for links):
<span style="cursor: auto">auto</span><br> <span style="cursor: crosshair">crosshair</span><br> <span style="cursor: default">default</span><br> <span style="cursor: e-resize">e-resize</span><br> <span style="cursor: help">help</span><br> <span style="cursor: move">move</span><br> <span style="cursor: n-resize">n-resize</span><br> <span style="cursor: ne-resize">ne-resize</span><br> <span style="cursor: nw-resize">nw-resize</span><br> <span style="cursor: pointer">pointer</span><br> <span style="cursor: progress">progress</span><br> <span style="cursor: s-resize">s-resize</span><br> <span style="cursor: se-resize">se-resize</span><br> <span style="cursor: sw-resize">sw-resize</span><br> <span style="cursor: text">text</span><br> <span style="cursor: w-resize">w-resize</span><br> <span style="cursor: wait">wait</span>
CSS Lists (#23)
Unordered Lists:
- Coffee
- Tea
- Coca Cola
- Coffee
- Tea
- Coca Cola
Ordered Lists:
- Coffee
- Tea
- Coca Cola
- Coffee
- Tea
- Coca Cola
HTML Lists and CSS List Properties
In HTML, there are two main types of lists:
- unordered lists (<ul>) – the list items are marked with bullets
- ordered lists (<ol>) – the list items are marked with numbers or letters
The CSS list properties allow you to:
- Set different list item markers for ordered lists
- Set different list item markers for unordered lists
- Set an image as the list item marker
- Add background colors to lists and list items
Different List Item Markers
The list-style-type
property specifies the type of list item marker.
The following example shows some of the available list item markers:
Example
ul.a {
list-style-type: circle;
}
ul.b {
list-style-type: square;
}
ol.c {
list-style-type: upper-roman;
}
ol.d {
list-style-type: lower-alpha;
}
Note: Some of the values are for unordered lists, and some for ordered lists.
An Image as The List Item Marker
The list-style-image
property specifies an image as the list item marker:
Example
ul {
list-style-image: url('sqpurple.gif');
}
Position The List Item Markers
The list-style-position
property specifies the position of the list-item markers (bullet points).
“list-style-position: outside;” means that the bullet points will be outside the list item. The start of each line of a list item will be aligned vertically. This is default:
- Coffee – A brewed drink prepared from roasted coffee beans…
- Tea
- Coca-cola
“list-style-position: inside;” means that the bullet points will be inside the list item. As it is part of the list item, it will be part of the text and push the text at the start:
- Coffee – A brewed drink prepared from roasted coffee beans…
- Tea
- Coca-cola
Example
ul.a {
list-style-position: outside;
}
ul.b {
list-style-position: inside;
}
Remove Default Settings
The list-style-type:none
property can also be used to remove the markers/bullets. Note that the list also has default margin and padding. To remove this, add margin:0
and padding:0
to <ul> or <ol>:
Example
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
List – Shorthand property
The list-style
property is a shorthand property. It is used to set all the list properties in one declaration:
Example
ul {
list-style: square inside url("sqpurple.gif");
}
When using the shorthand property, the order of the property values are:
list-style-type
(if a list-style-image is specified, the value of this property will be displayed if the image for some reason cannot be displayed)list-style-position
(specifies whether the list-item markers should appear inside or outside the content flow)list-style-image
(specifies an image as the list item marker)
If one of the property values above are missing, the default value for the missing property will be inserted, if any.
Styling List With Colors
We can also style lists with colors, to make them look a little more interesting.
Anything added to the <ol> or <ul> tag, affects the entire list, while properties added to the <li> tag will affect the individual list items:
Example
ol {
background: #ff9999;
padding: 20px;
}
ul {
background: #3399ff;
padding: 20px;
}
ol li {
background: #ffe5e5;
color: darkred;
padding: 5px;
margin-left: 35px;
}
ul li {
background: #cce5ff;
color: darkblue;
margin: 5px;
}
Result:
- Coffee
- Tea
- Coca Cola
- Coffee
- Tea
- Coca Cola
CSS Tables (#24)
The look of an HTML table can be greatly improved with CSS:
Company | Contact | Country |
---|---|---|
Alfreds Futterkiste | Maria Anders | Germany |
Berglunds snabbköp | Christina Berglund | Sweden |
Centro comercial Moctezuma | Francisco Chang | Mexico |
Ernst Handel | Roland Mendel | Austria |
Island Trading | Helen Bennett | UK |
Königlich Essen | Philip Cramer | Germany |
Laughing Bacchus Winecellars | Yoshi Tannamuri | Canada |
Magazzini Alimentari Riuniti | Giovanni Rovelli | Italy |
Table Borders
To specify table borders in CSS, use the border
property.
The example below specifies a solid border for <table>, <th>, and <td> elements:
Firstname | Lastname |
---|---|
Peter | Griffin |
Lois | Griffin |
Example
table, th, td {
border: 1px solid;
}
Full-Width Table
The table above might seem small in some cases. If you need a table that should span the entire screen (full-width), add width: 100%
to the <table> element:
Firstname | Lastname |
---|---|
Peter | Griffin |
Lois | Griffin |
Example
table {
width: 100%;
}
Double Borders
Notice that the table in the examples above have double borders. This is because both the table and the <th> and <td> elements have separate borders.
To remove double borders, take a look at the example below.
Collapse Table Borders
The border-collapse
property sets whether the table borders should be collapsed into a single border:
Firstname | Lastname |
---|---|
Peter | Griffin |
Lois | Griffin |
Example
table {
border-collapse: collapse;
}
If you only want a border around the table, only specify the border
property for <table>:
Firstname | Lastname |
---|---|
Peter | Griffin |
Lois | Griffin |
Example
table {
border: 1px solid;
}
CSS Table Size (#25)
Table Width and Height
The width and height of a table are defined by the width
and height
properties.
The example below sets the width of the table to 100%, and the height of the <th> elements to 70px:
Firstname | Lastname | Savings |
---|---|---|
Peter | Griffin | $100 |
Lois | Griffin | $150 |
Joe | Swanson | $300 |
Example
table {
width: 100%;
}
th {
height: 70px;
}
To create a table that should only span half the page, use width: 50%
:
Firstname | Lastname | Savings |
---|---|---|
Peter | Griffin | $100 |
Lois | Griffin | $150 |
Joe | Swanson | $300 |
Example
table {
width: 50%;
}
CSS Table Style (#26)
Table Padding
To control the space between the border and the content in a table, use the padding
property on <td> and <th> elements:
First Name | Last Name | Savings |
---|---|---|
Peter | Griffin | $100 |
Lois | Griffin | $150 |
Joe | Swanson | $300 |
Example
th, td {
padding: 15px;
text-align: left;
}
Horizontal Dividers
First Name | Last Name | Savings |
---|---|---|
Peter | Griffin | $100 |
Lois | Griffin | $150 |
Joe | Swanson | $300 |
Add the border-bottom
property to <th> and <td> for horizontal dividers:
Example
th, td {
border-bottom: 1px solid #ddd;
}
Hoverable Table
Use the :hover
selector on <tr> to highlight table rows on mouse over:
First Name | Last Name | Savings |
---|---|---|
Peter | Griffin | $100 |
Lois | Griffin | $150 |
Joe | Swanson | $300 |
Example
tr:hover {background-color: coral;}
Striped Tables
First Name | Last Name | Savings |
---|---|---|
Peter | Griffin | $100 |
Lois | Griffin | $150 |
Joe | Swanson | $300 |
For zebra-striped tables, use the nth-child()
selector and add a background-color
to all even (or odd) table rows:
Example
tr:nth-child(even) {background-color: #f2f2f2;}
Table Color
The example below specifies the background color and text color of <th> elements:
First Name | Last Name | Savings |
---|---|---|
Peter | Griffin | $100 |
Lois | Griffin | $150 |
Joe | Swanson | $300 |
Example
th {
background-color: #04AA6D;
color: white;
}
CSS Layout – The display Property (#27)
The display
property is the most important CSS property for controlling layout.
The display Property
The display
property specifies if/how an element is displayed.
Every HTML element has a default display value depending on what type of element it is. The default display value for most elements is block
or inline
.
Click to show panel
Block-level Elements
A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).
Examples of block-level elements:
-
<div>
-
<h1> - <h6>
-
<p>
-
<form>
-
<header>
-
<footer>
-
<section>
Inline Elements
An inline element does not start on a new line and only takes up as much width as necessary.
This is an inline <span> element inside a paragraph.
Examples of inline elements:
-
<span>
-
<a>
-
<img>
Display: none;
display: none;
is commonly used with JavaScript to hide and show elements without deleting and recreating them. Take a look at our last example on this page if you want to know how this can be achieved.
The <script>
element uses display: none;
as default.
Override The Default Display Value
As mentioned, every element has a default display value. However, you can override this.
Changing an inline element to a block element, or vice versa, can be useful for making the page look a specific way, and still follow the web standards.
A common example is making inline <li>
elements for horizontal menus:
Example
li {
display: inline;
}
Note: Setting the display property of an element only changes how the element is displayed, NOT what kind of element it is. So, an inline element with display: block;
is not allowed to have other block elements inside it.
The following example displays <span> elements as block elements:
Example
span {
display: block;
}
The following example displays <a> elements as block elements:
Example
a {
display: block;
}
Hide an Element – display:none or visibility:hidden?
display:none
visibility:hidden
Reset
Hiding an element can be done by setting the display
property to none
. The element will be hidden, and the page will be displayed as if the element is not there:
Example
h1.hidden {
display: none;
}
visibility:hidden;
also hides an element.
However, the element will still take up the same space as before. The element will be hidden, but still affect the layout:
Example
h1.hidden {
visibility: hidden;
}
CSS Layout – width and max-width (#28)
Using width, max-width and margin: auto;
As mentioned in the previous chapter; a block-level element always takes up the full width available (stretches out to the left and right as far as it can).
Setting the width
of a block-level element will prevent it from stretching out to the edges of its container. Then, you can set the margins to auto, to horizontally center the element within its container. The element will take up the specified width, and the remaining space will be split equally between the two margins:
Note: The problem with the <div>
above occurs when the browser window is smaller than the width of the element. The browser then adds a horizontal scrollbar to the page.
Using max-width
instead, in this situation, will improve the browser’s handling of small windows. This is important when making a site usable on small devices:
Tip: Resize the browser window to less than 500px wide, to see the difference between the two divs!
Here is an example of the two divs above:
Example
div.ex1 {
width: 500px;
margin: auto;
border: 3px solid #73AD21;
}
div.ex2 {
max-width: 500px;
margin: auto;
border: 3px solid #73AD21;
}
CSS Layout – The position Property (#29)
The position
property specifies the type of positioning method used for an element (static, relative, fixed, absolute or sticky).
The position Property
The position
property specifies the type of positioning method used for an element.
There are five different position values:
static
relative
fixed
absolute
sticky
Elements are then positioned using the top, bottom, left, and right properties. However, these properties will not work unless the position
property is set first. They also work differently depending on the position value.
position: static;
HTML elements are positioned static by default.
Static positioned elements are not affected by the top, bottom, left, and right properties.
An element with position: static;
is not positioned in any special way; it is always positioned according to the normal flow of the page:
Here is the CSS that is used:
Example
div.static {
position: static;
border: 3px solid #73AD21;
}
position: relative;
An element with position: relative;
is positioned relative to its normal position.
Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element.
Here is the CSS that is used:
Example
div.relative {
position: relative;
left: 30px;
border: 3px solid #73AD21;
}
position: fixed;
An element with position: fixed;
is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element.
A fixed element does not leave a gap in the page where it would normally have been located.
Notice the fixed element in the lower-right corner of the page. Here is the CSS that is used:
Example
div.fixed {
position: fixed;
bottom: 0;
right: 0;
width: 300px;
border: 3px solid #73AD21;
}
position: fixed;
position: absolute;
An element with position: absolute;
is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).
However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.
Here is a simple example:
This <div> element has position: relative;
Here is the CSS that is used:
Example
div.relative {
position: relative;
width: 400px;
height: 200px;
border: 3px solid #73AD21;
}
div.absolute {
position: absolute;
top: 80px;
right: 0;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}
position: sticky;
An element with position: sticky;
is positioned based on the user’s scroll position.
A sticky element toggles between relative
and fixed
, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport – then it “sticks” in place (like position:fixed).
Note: Internet Explorer does not support sticky positioning. Safari requires a -webkit- prefix (see example below). You must also specify at least one of top
, right
, bottom
or left
for sticky positioning to work.
In this example, the sticky element sticks to the top of the page (top: 0
), when you reach its scroll position.
Example
div.sticky {
position: -webkit-sticky; /* Safari */
position: sticky;
top: 0;
background-color: green;
border: 2px solid #4CAF50;
}
Positioning Text In an Image
How to position text over an image:
Example
CSS Layout – The z-index Property (#30)
The z-index
property specifies the stack order of an element.
The z-index Property
When elements are positioned, they can overlap other elements.
The z-index
property specifies the stack order of an element (which element should be placed in front of, or behind, the others).
An element can have a positive or negative stack order:
This is a heading
Because the image has a z-index of -1, it will be placed behind the text.
Example
img {
position: absolute;
left: 0px;
top: 0px;
z-index: -1;
}
Note: z-index
only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display: flex elements).
Another z-index Example
Example
Here we see that an element with greater stack order is always above an element with a lower stack order:
<html> <head> <style> .container { position: relative; } .black-box { position: relative; z-index: 1; border: 2px solid black; height: 100px; margin: 30px; } .gray-box { position: absolute; z-index: 3; background: lightgray; height: 60px; width: 70%; left: 50px; top: 50px; } .green-box { position: absolute; z-index: 2; background: lightgreen; width: 35%; left: 270px; top: -15px; height: 100px; } </style> </head> <body> <div class="container"> <div class="black-box">Black box</div> <div class="gray-box">Gray box</div> <div class="green-box">Green box</div> </div> </body> </html>
Without z-index
If two positioned elements overlap each other without a z-index
specified, the element defined last in the HTML code will be shown on top.
Example
Same example as above, but here with no z-index specified:
<html> <head> <style> .container { position: relative; } .black-box { position: relative; border: 2px solid black; height: 100px; margin: 30px; } .gray-box { position: absolute; background: lightgray; height: 60px; width: 70%; left: 50px; top: 50px; } .green-box { position: absolute; background: lightgreen; width: 35%; left: 270px; top: -15px; height: 100px; } </style> </head> <body> <div class="container"> <div class="black-box">Black box</div> <div class="gray-box">Gray box</div> <div class="green-box">Green box</div> </div> </body> </html>
CSS Layout – float and clear (#31)
The CSS float
property specifies how an element should float.
The CSS clear
property specifies what elements can float beside the cleared element and on which side.
The float Property
The float
property is used for positioning and formatting content e.g. 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 defaultinherit
– The element inherits the float value of its parent
In its simplest use, the float
property can be used to wrap text around images.
Example – float: right;
The following example specifies that an image should float to the right in a text:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa.
Example
img {
float: right;
}
Example – float: left;
The following example specifies that an image should float to the left in a text:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa.
Example
img {
float: left;
}
Example – No float
In the following example the image will be displayed just where it occurs in the text (float: none;):
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa.
Example
img {
float: none;
}
Example – Float Next To Each Other
Normally div elements will be displayed on top of each other. However, if we use float: left
we can let elements float next to each other:
Example
div {
float: left;
padding: 15px;
}
.div1 {
background: red;
}
.div2 {
background: yellow;
}
.div3 {
background: green;
}
CSS Layout – clear and clearfix (#32)
The clear Property
When we use the float
property, and we want the next element below (not on right or left), we will have to use the clear
property.
The clear
property specifies what should happen with the element that is next to a floating element.
The clear
property can have one of the following values:
none
– The element is not pushed below left or right floated elements. This is defaultleft
– The element is pushed below left floated elementsright
– The element is pushed below right floated elementsboth
– The element is pushed below both left and right floated elementsinherit
– The element inherits the clear value from its parent
When clearing floats, you should match the clear to the float: 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 web page.
Example
This example clears the float to the left. Here, it means that the <div2> element is pushed below the left floated <div1> element:
div1 {
float: left;
}
div2 {
clear: left;
}
The clearfix Hack
If a floated element is taller than the containing element, it will “overflow” outside of its container. We can then add a clearfix hack to solve this problem:
Without Clearfix
With Clearfix
Example
.clearfix {
overflow: auto;
}
The overflow: auto
clearfix works well as long as you are able to keep control of your margins and padding (else you might see scrollbars). The new, modern clearfix hack however, is safer to use, and the following code is used for most webpages:
Example
.clearfix::after {
content: "";
clear: both;
display: table;
}
CSS Layout – display: inline-block (#33)
The display: inline-block Value
Compared to display: inline
, the major difference is that display: inline-block
allows to set a width and height on the element.
Also, with display: inline-block
, the top and bottom margins/paddings are respected, but with display: inline
they are not.
Compared to display: block
, the major difference is that display: inline-block
does not add a line-break after the element, so the element can sit next to other elements.
The following example shows the different behavior of display: inline
, display: inline-block
and display: block
:
Example
span.a {
display: inline; /* the default for span */
width: 100px;
height: 100px;
padding: 5px;
border: 1px solid blue;
background-color: yellow;
}
span.b {
display: inline-block;
width: 100px;
height: 100px;
padding: 5px;
border: 1px solid blue;
background-color: yellow;
}
span.c {
display: block;
width: 100px;
height: 100px;
padding: 5px;
border: 1px solid blue;
background-color: yellow;
}
Using inline-block to Create Navigation Links
One common use for display: inline-block
is to display list items horizontally instead of vertically. The following example creates horizontal navigation links:
Example
.nav {
background-color: yellow;
list-style-type: none;
text-align: center;
padding: 0;
margin: 0;
}
.nav li {
display: inline-block;
font-size: 20px;
padding: 20px;
}
CSS Layout – Horizontal & Vertical Align (#34)
Center elements
horizontally and vertically
Center Align Elements
To horizontally center a block element (like <div>), use margin: auto;
Setting the width of the element will prevent it from stretching out to the edges of its container.
The element will then take up the specified width, and the remaining space will be split equally between the two margins:
This div element is centered.
Example
.center {
margin: auto;
width: 50%;
border: 3px solid green;
padding: 10px;
}
Note: Center aligning has no effect if the width
property is not set (or set to 100%).
Center Align Text
To just center the text inside an element, use text-align: center;
This text is centered.
Example
.center {
text-align: center;
border: 3px solid green;
}
Center an Image
To center an image, set left and right margin to auto
and make it into a block
element:
Example
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 40%;
}
Left and Right Align – Using position
One method for aligning elements is to use position: absolute;
:
In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.
Example
.right {
position: absolute;
right: 0px;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}
Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.
Left and Right Align – Using float
Another method for aligning elements is to use the float
property:
Example
.right {
float: right;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}
The clearfix Hack
Note: If an element is taller than the element containing it, and it is floated, it will overflow outside of its container. You can use the “clearfix hack” to fix this (see example below).
Without Clearfix
With Clearfix
Then we can add the clearfix hack to the containing element to fix this problem:
Example
.clearfix::after {
content: "";
clear: both;
display: table;
}
Center Vertically – Using padding
There are many ways to center an element vertically in CSS. A simple solution is to use top and bottom padding
:
I am vertically centered.
Example
.center {
padding: 70px 0;
border: 3px solid green;
}
To center both vertically and horizontally, use padding
and text-align: center
:
I am vertically and horizontally centered.
Example
.center {
padding: 70px 0;
border: 3px solid green;
text-align: center;
}
Center Vertically – Using line-height
Another trick is to use the line-height
property with a value that is equal to the height
property:
I am vertically and horizontally centered.
Example
.center {
line-height: 200px;
height: 200px;
border: 3px solid green;
text-align: center;
}
/* If the text has multiple lines, add the following: */
.center p {
line-height: 1.5;
display: inline-block;
vertical-align: middle;
}
Center Vertically – Using position & transform
If padding
and line-height
are not options, another solution is to use positioning and the transform
property:
I am vertically and horizontally centered.
Example
.center {
height: 200px;
position: relative;
border: 3px solid green;
}
.center p {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Center Vertically – Using Flexbox
You can also use flexbox to center things. Just note that flexbox is not supported in IE10 and earlier versions:
Example
.center {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid green;
}
CSS Image Gallery (#35)
CSS can be used to create an image gallery.
Image Gallery
The following image gallery is created with CSS:
Example
<html> <head> <style> div.gallery { margin: 5px; border: 1px solid #ccc; float: left; width: 180px; } div.gallery:hover { border: 1px solid #777; } div.gallery img { width: 100%; height: auto; } div.desc { padding: 15px; text-align: center; } </style> </head> <body> <div class="gallery"> <a target="_blank" href="img_5terre.jpg"> <img src="img_5terre.jpg" alt="Cinque Terre" width="600" height="400"> </a> <div class="desc">Add a description of the image here</div> </div> <div class="gallery"> <a target="_blank" href="img_forest.jpg"> <img src="img_forest.jpg" alt="Forest" width="600" height="400"> </a> <div class="desc">Add a description of the image here</div> </div> <div class="gallery"> <a target="_blank" href="img_lights.jpg"> <img src="img_lights.jpg" alt="Northern Lights" width="600" height="400"> </a> <div class="desc">Add a description of the image here</div> </div> <div class="gallery"> <a target="_blank" href="img_mountains.jpg"> <img src="img_mountains.jpg" alt="Mountains" width="600" height="400"> </a> <div class="desc">Add a description of the image here</div> </div> </body> </html>
More Examples
Responsive Image Gallery
How to use CSS media queries to create a responsive image gallery that will look good on desktops, tablets and smart phones.
CSS Image Sprites (#36)
Image Sprites
An image sprite is a collection of images put into a single image.
A web page with many images can take a long time to load and generates multiple server requests.
Using image sprites will reduce the number of server requests and save bandwidth.
Image Sprites – Simple Example
Instead of using three separate images, we use this single image (“img_navsprites.gif”):
With CSS, we can show just the part of the image we need.
In the following example the CSS specifies which part of the “img_navsprites.gif” image to show:
Example
#home {
width: 46px;
height: 44px;
background: url(img_navsprites.gif) 0 0;
}
Example explained:
<img id="home" src="img_trans.gif">
– Only defines a small transparent image because the src attribute cannot be empty. The displayed image will be the background image we specify in CSSwidth: 46px; height: 44px;
– Defines the portion of the image we want to usebackground: url(img_navsprites.gif) 0 0;
– Defines the background image and its position (left 0px, top 0px)
This is the easiest way to use image sprites, now we want to expand it by using links and hover effects.
Image Sprites – Create a Navigation List
We want to use the sprite image (“img_navsprites.gif”) to create a navigation list.
We will use an HTML list, because it can be a link and also supports a background image:
Example
#navlist {
position: relative;
}
#navlist li {
margin: 0;
padding: 0;
list-style: none;
position: absolute;
top: 0;
}
#navlist li, #navlist a {
height: 44px;
display: block;
}
#home {
left: 0px;
width: 46px;
background: url('img_navsprites.gif') 0 0;
}
#prev {
left: 63px;
width: 43px;
background: url('img_navsprites.gif') -47px 0;
}
#next {
left: 129px;
width: 43px;
background: url('img_navsprites.gif') -91px 0;
}
Example explained:
- #navlist {position:relative;} – position is set to relative to allow absolute positioning inside it
- #navlist li {margin:0;padding:0;list-style:none;position:absolute;top:0;} – margin and padding are set to 0, list-style is removed, and all list items are absolute positioned
- #navlist li, #navlist a {height:44px;display:block;} – the height of all the images are 44px
Now start to position and style for each specific part:
- #home {left:0px;width:46px;} – Positioned all the way to the left, and the width of the image is 46px
- #home {background:url(img_navsprites.gif) 0 0;} – Defines the background image and its position (left 0px, top 0px)
- #prev {left:63px;width:43px;} – Positioned 63px to the right (#home width 46px + some extra space between items), and the width is 43px.
- #prev {background:url(‘img_navsprites.gif’) -47px 0;} – Defines the background image 47px to the right (#home width 46px + 1px line divider)
- #next {left:129px;width:43px;}- Positioned 129px to the right (start of #prev is 63px + #prev width 43px + extra space), and the width is 43px.
- #next {background:url(‘img_navsprites.gif’) -91px 0;} – Defines the background image 91px to the right (#home width 46px + 1px line divider + #prev width 43px + 1px line divider )
Image Sprites – Hover Effect
Now we want to add a hover effect to our navigation list.
Tip: The :hover
selector can be used on all elements, not only on links.
Our new image (“img_navsprites_hover.gif”) contains three navigation images and three images to use for hover effects:
Because this is one single image, and not six separate files, there will be no loading delay when a user hovers over the image.
We only add three lines of code to add the hover effect:
Example
#home a:hover {
background: url('img_navsprites_hover.gif') 0 -45px;
}
#prev a:hover {
background: url('img_navsprites_hover.gif') -47px -45px;
}
#next a:hover {
background: url('img_navsprites_hover.gif') -91px -45px;
}
Example explained:
- #home a:hover {background: url(‘img_navsprites_hover.gif’) 0 -45px;} – For all three hover images we specify the same background position, only 45px further down
CSS Website Layout (#37)
Website Layout
A website is often divided into headers, menus, content and a footer:
There are tons of different layout designs to choose from. However, the structure above, is one of the most common, and we will take a closer look at it in this tutorial.
Header
A header is usually located at the top of the website (or right below a top navigation menu). It often contains a logo or the website name:
Example
.header {
background-color: #F1F1F1;
text-align: center;
padding: 20px;
}
Result:
Header
Navigation Bar
A navigation bar contains a list of links to help visitors navigating through your website:
Example
/* The navbar container */
.topnav {
overflow: hidden;
background-color: #333;
}
/* Navbar links */
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
/* Links - change color on hover */
.topnav a:hover {
background-color: #ddd;
color: black;
}
Result
Content
The layout in this section, often depends on the target users. The most common layout is one (or combining them) of the following:
- 1-column (often used for mobile browsers)
- 2-column (often used for tablets and laptops)
- 3-column layout (only used for desktops)
1-column:
2-column:
3-column:
We will create a 3-column layout, and change it to a 1-column layout on smaller screens:
Example
/* Create three equal columns that float next to each other */
.column {
float: left;
width: 33.33%;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
/* Responsive layout - makes the three columns stack on top of each other instead of next to each other on smaller screens (600px wide or less) */
@media screen and (max-width: 600px) {
.column {
width: 100%;
}
}
Result
Column
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique.
Column
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique.
Column
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique.
Tip: To create a 2-column layout, change the width to 50%. To create a 4-column layout, use 25%, etc.
Tip: A more modern way of creating column layouts, is to use CSS Flexbox. However, it is not supported in Internet Explorer 10 and earlier versions. If you require IE6-10 support, use floats (as shown above).
Unequal Columns
The main content is the biggest and the most important part of your site.
It is common with unequal column widths, so that most of the space is reserved for the main content. The side content (if any) is often used as an alternative navigation or to specify information relevant to the main content. Change the widths as you like, only remember that it should add up to 100% in total:
Example
.column {
float: left;
}
/* Left and right column */
.column.side {
width: 25%;
}
/* Middle column */
.column.middle {
width: 50%;
}
/* Responsive layout - makes the three columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) {
.column.side, .column.middle {
width: 100%;
}
}
Result:
Side
Lorem ipsum dolor sit amet, consectetur adipiscing elit…
Main Content
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique. Quisque vehicula, risus eget aliquam placerat, purus leo tincidunt eros, eget luctus quam orci in velit. Praesent scelerisque tortor sed accumsan convallis.
Side
Lorem ipsum dolor sit amet, consectetur adipiscing elit…
Footer
The footer is placed at the bottom of your page. It often contains information like copyright and contact info:
Example
.footer {
background-color: #F1F1F1;
text-align: center;
padding: 10px;
}
Result:
CSS Math Functions (#38)
The CSS math functions allow mathematical expressions to be used as property values. Here, we will explain the calc()
, max()
and min()
functions.
The calc() Function
The calc()
function performs a calculation to be used as the property value.
CSS Syntax
calc(expression)
Value | Description |
---|---|
expression | Required. A mathematical expression. The result will be used as the value. The following operators can be used: + – * / |
Let us look at an example:
Example
Use calc() to calculate the width of a <div> element:
#div1 {
position: absolute;
left: 50px;
width: calc(100% - 100px);
border: 1px solid black;
background-color: yellow;
padding: 5px;
}
The max() Function
The max()
function uses the largest value, from a comma-separated list of values, as the property value.
CSS Syntax
max(value1, value2, …)
Value | Description |
---|---|
value1, value2, … | Required. A list of comma-separated values – where the largest value is chosen |
Let us look at an example:
Example
Use max() to set the width of #div1 to whichever value is largest, 50% or 300px:
#div1 {
background-color: yellow;
height: 100px;
width: max(50%, 300px);
}
The min() Function
The min()
function uses the smallest value, from a comma-separated list of values, as the property value.
CSS Syntax
min(value1, value2, …)
Value | Description |
---|---|
value1, value2, … | Required. A list of comma-separated values – where the smallest value is chosen |
Let us look at an example:
Example
Use min() to set the width of #div1 to whichever value is smallest, 50% or 300px:
#div1 {
background-color: yellow;
height: 100px;
width: min(50%, 300px);
}
All CSS Math Functions
Function | Description |
---|---|
calc() | Allows you to perform calculations to determine CSS property values |
max() | Uses the largest value, from a comma-separated list of values, as the property value |
min() | Uses the smallest value, from a comma-separated list of values, as the property value |