CSS Tutorial
CSS Tutorial
CSS Tutorial
CSS Introduction:
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
<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 (W3C) created CSS.
With an external stylesheet file, you can change the look of an entire website by
changing just one file!
CSS Syntax:
A CSS rule-set consists of a selector and a declaration block:
A CSS declaration always ends with a semicolon, 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;
}
CSS Comments
Comments are used to explain the code, and may help when you edit the
source code at a later date.
A CSS comment starts with /* and ends with */. Comments can also span
multiple lines:
CSS Selectors:
CSS selectors are used to "find" (or select) the HTML elements you want to
style.
In this example all <p> elements 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.
To select an element with a specific id, write a hash (#) character, followed by
the id of the element.
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!
To select elements with a specific class, write a period (.) character, followed by
the class name.
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.
p.center {
text-align: center;
color: red;
}
HTML elements can also refer to more than one class.
In this example the <p> element will be styled according to class="center" and
to class="large":
The CSS rule below will affect every HTML element on the page:
* {
text-align: center;
color: blue;
}
h1, h2, p {
text-align: center;
color: red;
}
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.
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
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.
Note: Do not add a space between the property value and the unit (such
as margin-left: 20 px;). The correct way is: 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.
<style>
body {
background-color: linen;
}
</style>
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.
If the internal style is defined after the link to the external style sheet, the
internal style will be used. However, if the internal style is defined before the
link to the external style sheet, the external style will be used.
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:
So, an inline style has the highest priority, and will override external and
internal styles and browser defaults.
CSS Colors:
Colors are specified using predefined color names, or RGB, HEX, HSL, RGBA,
HSLA values.
#rrggbb
Each parameter (red, green, and blue) defines the intensity of the color
between 0 and 255.
HSL Value
In CSS, a color can be specified using hue, saturation, and lightness (HSL) in
the form:
RGBA Value
RGBA color values are an extension of RGB color values with an alpha channel -
which specifies the opacity for a color.
CSS Backgrounds:
CSS background-color
The background-color property specifies the background color of an element.
background-color: lightblue;
CSS background-image
The background-image property specifies an image to use as the background of
an element.
background-image: url("paper.gif");
Note: When using a background image, use an image that does not disturb the
text.
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.
background-repeat: repeat-x;
background-repeat: no-repeat;
CSS background-position
The background-position property is used to specify the position of the
background image.
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):
background-attachment: fixed;
Specify that the background image should scroll with the rest of the page:
background-attachment: scroll;
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.
CSS Borders:
CSS Border Style
The border-style property specifies what kind of border to display.
The border-style property can have from one to four values (for the top
border, right border, bottom border, and the left border).
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.
The border-width property can have from one to four values (for the top
border, right border, bottom border, and the left border).
The border-color property can have from one to four values (for the top
border, right border, bottom border, and the left border).
p {
border-top-style: dotted;
border-right-style: solid;
border-bottom-style: dotted;
border-left-style: solid;
}
border-style: dotted;
o all four borders are dotted
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
You can also specify all the individual border properties for just one side:
border-left: 6px solid red;
border-radius: 5px;
Note: The border-radius property is not supported in IE8 and earlier versions.
CSS Margins:
The CSS margin properties are used to create space around elements, outside
of any defined borders.
margin-top
margin-right
margin-bottom
margin-left
p {
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
}
The margin property is a shorthand property for the following individual margin
properties:
margin: 25px;
o all four margins are 25px
margin: 25px;
The element will then take up the specified width, and the remaining space will
be split equally between the left and right margins.
margin: auto;
div {
border: 1px solid red;
margin-left: 100px;
}
p.ex1 {
margin-left: inherit;
}
Margin Collapse
Top and bottom margins of elements are sometimes collapsed into a single
margin that is equal to the largest of the two margins.
This does not happen on left and right margins! Only top and bottom margins!
Look at the following example:
h1 {
margin: 0 0 50px 0;
}
h2 {
margin: 20px 0 0 0;
}
In the example above, the <h1> element has a bottom margin of 50px and the
<h2> element has a top margin set to 20px.
Common sense would seem to suggest that the vertical margin between the
<h1> and the <h2> would be a total of 70px (50px + 20px). But due to margin
collapse, the actual margin ends up being 50px.
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-top
padding-right
padding-bottom
padding-left
div {
padding-top: 50px;
padding-right: 30px;
padding-bottom: 50px;
padding-left: 80px;
}
padding: 25px;
o all four paddings are 25px
padding: 25px;
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.
EX: 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 width; if you
increase the padding, the available content space will decrease.
div {
width: 300px;
padding: 25px;
box-sizing: border-box;
}
CSS 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.
auto - This is default. The browser calculates the height and width
length - Defines the height/width in px, cm etc.
% - Defines the height/width in percent of the containing block
initial - Sets the height/width to its default value
inherit - The height/width will be inherited from its parent value
div {
height: 200px;
width: 50%;
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.
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:
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.
Demonstration of the box model:
div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
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.
320px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 0px (left + right margin)
= 350px
Total element width = width + left padding + right padding + left border + right
border + left margin + right margin
Total element height = height + top padding + bottom padding + top border +
bottom border + top margin + bottom margin
CSS Outline:
An outline is a line that is drawn around elements, OUTSIDE the borders, to
make the element "stand out".
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.
Note: None of the other outline properties will have any effect, unless
the outline-style property is set!
outline-color: red;
outline-color: invert;
outline-width
outline-style (required)
outline-color
The outline property is specified as one, two, or three values from the list
above. The order of the values does not matter.
The following example specifies an outline 15px outside the border edge:
outline-offset: 15px;
p {
margin: 30px;
border: 1px solid black;
outline: 1px solid red;
outline-offset: 15px;
}
CSS Text:
Text Color
The color property is used to set the color of the text. The color is specified by:
The default text color for a page is defined in the body selector.
body {
color: blue;
}
h1 {
color: green;
}
Note: For W3C compliant CSS: If you define the color property, you must also
define the background-color.
Text Alignment
The text-align property is used to set the horizontal alignment of a text.
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):
text-align: center;
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):
text-align: justify;
Text Decoration
The text-decoration property is used to set or remove decorations from text.
a { text-decoration: none; }
The other text-decoration values are used to decorate text:
text-decoration: overline;
text-decoration: line-through;
text-decoration: underline;
Note: It is not recommended to underline text that is not a link, as this often
confuses the reader.
Text Transformation
The text-transform property is used to specify uppercase and lowercase letters
in a text.
Text Indentation
The text-indent property is used to specify the indentation of the first line of a
text (insert space before first word):
text-indent: 50px;
Letter Spacing
The letter-spacing property is used to specify the space between the
characters in a text.
h1 {letter-spacing: 3px;}
h2 {letter-spacing: -3px;}
Line Height
The line-height property is used to specify the space between lines:
direction: rtl;
Word Spacing
The word-spacing property is used to specify the space between the words in a
text.
h1 {word-spacing: 10px;}
h2 {word-spacing: -5px;}
Text Shadow
The text-shadow property adds shadow to text.
The following example specifies the position of the horizontal shadow (3px), the
position of the vertical shadow (2px) and the color of the shadow (red):
Note: Internet Explorer 9 and earlier do not support the text-shadow property.
CSS Fonts:
The CSS font properties define the font family, boldness, size, and the style of a
text.
Difference Between Serif and Sans-serif
generic family - a group of font families with a similar look (like "Serif"
or "Monospace")
font family - a specific font family (like "Times New Roman" or "Arial")
Serif Times New Roman Serif fonts have small lines at the
Georgia ends on some characters
Note: On computer screens, sans-serif fonts are considered easier to read than
serif fonts.
Font Family
The font family of a text is set with the font-family property.
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.
Note: If the name of a font family is more than one word, it must be in
quotation marks, like: "Times New Roman".
Font Style
The font-style property is mostly used to specify italic text.
Font Size
The font-size property sets the size of the text.
Being able to manage the text size is important in web design. However, you
should not use font size adjustments to make paragraphs look like headings, or
headings look like paragraphs.
Always use the proper HTML tags, like <h1> - <h6> for headings and <p> for
paragraphs.
Absolute size:
Relative size:
Note: If you do not specify a font size, the default size for normal text, like
paragraphs, is 16px (16px=1em).
font-size: 40px;
Tip: If you use pixels, you can still use the zoom tool to resize the entire page.
1em is equal to the current font size. The default text size in browsers is 16px.
So, the default size of 1em is 16px.
The size can be calculated from pixels to em using this formula: pixels/16=em
Unfortunately, there is still a problem with older versions of IE. The text
becomes larger than it should when made larger, and smaller than it should
when made smaller.
body {
font-size: 100%;
}
h1 {
font-size: 2.5em;
}
Our code now works great! It shows the same text size in all browsers, and
allows all browsers to zoom or resize the text!
Font Weight
The font-weight property specifies the weight of a font:
That way the text size will follow the size of the browser window.
CSS Icons:
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.)
<script src="https://kit.fontawesome.com/yourcode.js"></script>
<body>
<i class="fas fa-cloud"></i>
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.mi
n.css">
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">
<i class="material-icons">cloud</i>
a {color: hotpink;}
In addition, links can be styled differently depending on what state they are in.
/* unvisited link */
a:link {color: red;}
/* visited link */
a:visited {color: green;}
/* selected link */
a:active {color: blue;}
When setting the style for several link states, there are some order rules:
Text Decoration
The text-decoration property is mostly used to remove underlines from links:
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;
}
CSS Lists:
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 following example shows some of the available list item markers:
ul {list-style-image: url('sqpurple.gif');}
"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.
"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.
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
When using the shorthand property, the order of the property values are:
If one of the property values above are missing, the default value for the
missing property will be inserted, if any.
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:
ol {background: #ff9999; }
ol li {background: #ffe5e5;}
CSS Tables:
Table Borders
To specify table borders in CSS, use the border property.
The example below specifies a black border for <table>, <th>, and <td>
elements:
Firstname Lastname
Peter Griffin
Lois Griffin
Notice that the table in the example above has double borders. This is because
both the table and the <th> and <td> elements have separate borders.
Firstname Lastname
Peter Griffin
Lois Griffin
If you only want a border around the table, only specify the border property for
<table>:
Firstname Lastname
Peter Griffin
Lois Griffin
The example below sets the width of the table to 100%, and the height of the
<th> elements to 50px:
th {height: 50px;}
Vertical Alignment
The vertical-align property sets the vertical alignment (like top, bottom, or
middle) of the content in <th> or <td>.
By default, the vertical alignment of the content in a table is middle (for both
<th> and <td> elements).
The following example sets the vertical text alignment to bottom for <td>
elements:
td {height: 50px;
vertical-align: bottom;}
Table Padding
To control the space between the border and the content in a table, use
the padding property on <td> and <th> elements:
Horizontal Dividers
Add the border-bottom property to <th> and <td> for horizontal dividers:
Striped Tables
For zebra-striped tables, use the nth-child() selector and add a background-
color to all even (or odd) table rows:
Table Color
The example below specifies the background color and text color of <th>
elements:
th {background-color: #4CAF50;
color: white;}
Responsive Table
A responsive table will display a horizontal scroll bar if the screen is too small to
display the full content:
Add a container element (like <div>) with overflow-x:auto around the <table>
element to make it responsive:
<div style="overflow-x:auto;">
<table>
... table content ...
</table>
</div>
Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown
when being used (even though "overflow:scroll" is set).
CSS Layout - The display Property:
The display property is the most important CSS property for controlling
layout.
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.
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).
<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.
Display: none;
display: none; is commonly used with JavaScript to hide and show elements
without deleting and recreating them.
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.
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.
a {display: block;}
However, the element will still take up the same space as before. The element
will be hidden, but still affect the layout:
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:
div.ex1 {
width: 500px;
margin: auto;
border: 3px solid #73AD21;
}
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:
div.ex2 {
max-width: 500px;
margin: auto;
border: 3px solid #73AD21;
}
CSS Layout - The position Property:
The position property specifies the type of positioning method used for an
element.
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.
div.static {
position: static;
border: 3px solid #73AD21;}
position: relative;
An element with position: relative; is positioned relative to its normal
position.
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.
div.fixed {
position: fixed;
bottom: 0;
right: 0;
width: 300px;
border: 3px solid #73AD21;}
position: absolute;
An element with position: absolute; is positioned relative to the nearest
positioned ancestor (instead of positioned relative to the viewport, like fixed).
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, Edge 15 and earlier versions do 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.
div.sticky {
position: -webkit-sticky; /* Safari */
position: sticky;
top: 0;
background-color: green;
border: 2px solid #4CAF50;}
Overlapping Elements
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).
img {
position: absolute;
left: 0px;
top: 0px;
z-index: -1;}
CSS Layout – Overflow:
The overflow property specifies whether to clip the content or to add scrollbars
when the content of an element is too big to fit in the specified area.
Note: The overflow property only works for block elements with a specified
height.
Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown
when being used (even though "overflow:scroll" is set).
overflow: visible
By default, the overflow is visible, meaning that it is not clipped and it renders
outside the element's box:
overflow: hidden
With the hidden value, the overflow is clipped, and the rest of the content is
hidden:
overflow: scroll
Setting the value to scroll, the overflow is clipped and a scrollbar is added to
scroll inside the box. Note that this will add a scrollbar both horizontally and
vertically (even if you do not need it):
div {overflow: scroll;}
overflow: auto
The auto value is similar to scroll, but it adds scrollbars only when necessary:
div {
overflow-x: hidden; /* Hide horizontal scrollbar */
overflow-y: scroll; /* Add vertical scrollbar */
}
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:
Example - No float
In the following example the image will be displayed just where it occurs in the
text (float: none;):
The most common way to use the clear property is after you have used
a float property on an element.
When clearing floats, you should match the clear to the float: 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.
The following example clears the float to the left. Means that no floating
elements are allowed on the left side (of the div):
Without Clearfix
With Clearfix
Then we can add overflow: auto; to the containing element to fix this
problem:
.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:
.clearfix::after {
content: "";
clear: both;
display: table;}
.box {
float: left;
width: 33.33%; /* three boxes (use 25% for four, and 50% for two) */
padding: 50px; /* if you want space between the images */}
What is box-sizing?
You can easily create three floating boxes side by side. However, when you add
something that enlarges the width of each box (e.g. padding or borders), the
box will break. The box-sizing property allows us to include the padding and
border in the box's total width (and height), making sure that the padding stays
inside of the box and that it does not break.
Also, with display: inline-block, the top and bottom margins/paddings are
respected, but with display: inline they are not.
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:
.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 {
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:
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;:
position: absolute;
right: 0px;
Note: Absolute positioned elements are removed from the normal flow, and can
overlap elements.
float: right;
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.
.center {
padding: 70px 0;}
.center {
padding: 70px 0;
text-align: center;}
.center {
height: 200px;
position: relative;
border: 3px solid green;}
.center p {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);}
CSS Combinators:
A combinator is something that explains the relationship between the selectors.
A CSS selector can contain more than one simple selector. Between the simple
selectors, we can include a combinator.
Descendant Selector
The descendant selector matches all elements that are descendants of a
specified element.
The following example selects all <p> elements inside <div> elements:
Child Selector
The child selector selects all elements that are the children of a specified
element.
The following example selects all <p> elements that are children of a <div>
element:
The following example selects all <p> elements that are placed immediately
after <div> elements:
The following example selects all <p> elements that are siblings of <div>
elements:
CSS Pseudo-classes:
A pseudo-class is used to define a special state of an element.
Syntax
selector:pseudo-class {
property:value;
}
Anchor Pseudo-classes
Links can be displayed in different ways:
/* unvisited link */
a:link {color: #FF0000;}
/* visited link */
a:visited {color: #00FF00;}
/* selected link */
a:active {color: #0000FF;}
Note: a:hover MUST come after a:link and a:visited in the CSS definition in
order to be effective! a:active MUST come after a:hover in the CSS definition
in order to be effective! Pseudo-class names are not case-sensitive.
When you hover over the link in the example, it will change color:
Hover on <div>
An example of using the :hover pseudo-class on a <div> element:
p {
display: none;
background-color: yellow;
padding: 20px;}
div:hover p {
display: block;}
CSS - The :first-child Pseudo-class
The :first-child pseudo-class matches a specified element that is the first
child of another element.
Note: For :first-child to work in IE8 and earlier, a DOCTYPE must be declared.
In the example below, :lang defines the quotation marks for <q> elements with
lang="no":
<style>
q:lang(no) {
quotes: "~" "~";
}
</style>
<body>
<p>Some text <q lang="no">A quote in a paragraph</q> Some text.</p>
</body>
Note: IE8 supports the :lang pseudo class only if a !DOCTYPE is specified.
CSS Pseudo-elements:
A CSS pseudo-element is used to style specified parts of an element.
Syntax
selector::pseudo-element {
property:value;
}
The single-colon syntax was used for both pseudo-classes and pseudo-elements
in CSS2 and CSS1.
For backward compatibility, the single-colon syntax is acceptable for CSS2 and
CSS1 pseudo-elements.
The ::first-line Pseudo-element
The ::first-line pseudo-element is used to add a special style to the first line
of a text.
The following example formats the first line of the text in all <p> elements:
p::first-line {
color: #ff0000;
font-variant: small-caps;}
The following example formats the first letter of the text in all <p> elements:
p::first-letter {
color: #ff0000;
font-size: xx-large;}
p.intro::first-letter {
color: #ff0000;
font-size:200%;}
The example above will display the first letter of paragraphs with class="intro",
in red and in a larger size.
Multiple Pseudo-elements
Several pseudo-elements can also be combined.
In the following example, the first letter of a paragraph will be red, in an xx-
large font size. The rest of the first line will be blue, and in small-caps. The rest
of the paragraph will be the default font size and color:
p::first-letter {
color: #ff0000;
font-size: xx-large;}
p::first-line {
color: #0000ff;
font-variant: small-caps;}
The following example inserts an image before the content of each <h1>
element:
h1::before {
content: url(smiley.gif);}
CSS - The ::after Pseudo-element
The ::after pseudo-element can be used to insert some content after the
content of an element.
The following example inserts an image after the content of each <h1>
element:
h1::after {
content: url(smiley.gif);}
The following example makes the selected text red on a yellow background:
Transparent Image
The opacity property can take a value from 0.0 - 1.0. The lower value, the
more transparent:
Note: IE8 and earlier use filter:alpha(opacity=x). The x can take a value from 0
- 100. A lower value makes the element more transparent.
img {
opacity: 0.5;
filter: alpha(opacity=50); /* For IE8 and earlier */
}
Transparent Hover Effect
The opacity property is often used together with the :hover selector to change
the opacity on mouse-over:
img:hover {
opacity: 0.5;
filter: alpha(opacity=50); /* For IE8 and earlier */
}
Transparent Box
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:
div {
opacity: 0.3;
filter: alpha(opacity=30); /* For IE8 and earlier */
}
div {
background: rgba(76, 175, 80, 0.3) /*Green background with 30% opacity*/
}
#rcorners {
border-radius: 25px;
border: 2px solid #73AD21;
padding: 20px;
width: 200px;
height: 150px;}
Four values - border-radius: 15px 50px 30px 5px; (first value applies to
top-left corner, second value applies to top-right corner, third value applies to
bottom-right corner, and fourth value applies to bottom-left corner).
Three values - border-radius: 15px 50px 30px; (first value applies to top-
left corner, second value applies to top-right and bottom-left corners, and third
value applies to bottom-right corner).
Two values - border-radius: 15px 50px; (first value applies to top-left and
bottom-right corners, and the second value applies to top-right and bottom-left
corners).
One value - border-radius: 15px; (the value applies to all four corners, which
are rounded equally.
Rounded Image:
Circled Image:
text-shadow
box-shadow
In its simplest use, you only specify the horizontal shadow (2px) and the
vertical shadow (2px):
h1 {
color: white;
text-shadow: 2px 2px 4px #000000;}
Multiple Shadows
To add more than one shadow to the text, you can add a comma-separated list
of shadows.
The following example shows a red and blue neon glow shadow:
You can also use the text-shadow property to create a plain border around
some text (without shadows):
h1 {
color: yellow;
text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;}
In its simplest use, you only specify the horizontal shadow and the vertical
shadow:
You can also add shadows to the ::before and ::after pseudo-elements, to
create an interesting effect.
Cards
An example of using the box-shadow property to create paper-like cards:
div.card {
width: 250px;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
text-align: center;}
text-overflow
word-wrap
word-break
writing-mode
p.test1 {
white-space: nowrap;
width: 200px;
overflow: hidden;
text-overflow: clip;}
p.test2 {
white-space: nowrap;
width: 200px;
overflow: hidden;
text-overflow: ellipsis;}
CSS Word Wrapping
The CSS word-wrap property allows long words to be able to be broken and wrap
onto the next line.
The word-wrap property allows you to force the text to wrap - even if it means
splitting it in the middle of a word.
p {word-wrap: break-word;}
Note: The word-break property is not supported in Opera 12 and earlier versions.
Note: CSS Transitions does not work in Internet Explorer 9 and earlier versions.
Note: If the duration part is not specified, the transition will have no effect,
because the default value is 0.
The following example shows a 100px * 100px red <div> element. The <div>
element has also specified a transition effect for the width property, with a
duration of 2 seconds:
div {
width: 100px;
height: 100px;
background: red;
transition: width 2s;}
The transition effect will start when the specified CSS property (width) changes
value.
Now, let us specify a new value for the width property when a user mouses over
the <div> element:
div:hover {width: 300px;}
Notice that when the cursor mouses out of the element, it will gradually change
back to its original style.
ease - specifies a transition effect with a slow start, then fast, then end
slowly (this is default)
linear - specifies a transition effect with the same speed from start to
end
ease-in - specifies a transition effect with a slow start
ease-out - specifies a transition effect with a slow end
ease-in-out - specifies a transition effect with a slow start and end
cubic-bezier(n,n,n,n) - lets you define your own values in a cubic-
bezier function
The following example shows the some of the different speed curves that can be
used:
Transition + Transformation
The following example adds a transition effect to the transformation:
div {
transition-property: width;
transition-duration: 2s;
transition-timing-function: linear;
transition-delay: 1s;}
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.
With CSS, we can show just the part of the image we need.
#home {
width: 46px;
height: 44px;
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;}
In the body:
Example explained:
The following example selects all <a> elements with a target attribute:
The following example selects all elements with a title attribute that contains a
space-separated list of words, one of which is "flower":
The following example selects all elements with a class attribute value that
begins with "top":
Note: The value has to be a whole word, either alone, like class="top", or
followed by a hyphen( - ), like class="top-text"!
The following example selects all elements with a class attribute value that
begins with "top":
The following example selects all elements with a class attribute value that ends
with "test":
The following example selects all elements with a class attribute value that
contains "te":
Styling Forms
The attribute selectors can be useful for styling forms without class or ID.
CSS Forms:
Styling Input Fields
Use the width property to determine the width of the input field:
Padded Inputs
Use the padding property to add space inside the text field.
Tip: When you have many inputs after each other, you might also want to add
some margin, to add more space outside of them:
input[type=text] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;}
Note that we have set the box-sizing property to border-box. This makes sure
that the padding and eventually borders are included in the total width and
height of the elements.
Bordered Inputs
Use the border property to change the border size and color, and use
the border-radius property to add rounded corners:
input[type=text] {
border: 2px solid red;
border-radius: 4px;}
input[type=text] {
border: none;
border-bottom: 2px solid red;}
Colored Inputs
Use the background-color property to add a background color to the input, and
the color property to change the text color:
input[type=text] {
background-color: #3CBC8D;
color: white;}
Focused Inputs
By default, some browsers will add a blue outline around the input when it gets
focus (clicked on). You can remove this behavior by adding outline: none; to
the input.
Use the :focus selector to do something with the input field when it gets focus:
input[type=text] {
background-color: white;
background-image: url('searchicon.png');
background-position: 10px 10px;
background-repeat: no-repeat;
padding-left: 40px;}
input[type=text] {
-webkit-transition: width 0.4s ease-in-out;
transition: width 0.4s ease-in-out;}
input[type=text]:focus {width: 100%;}
Styling Textareas
Tip: Use the resize property to prevent textareas from being resized (disable
the "grabber" in the bottom right corner):
textarea {
width: 100%;
height: 150px;
padding: 12px 20px;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
background-color: #f8f8f8;
resize: none;
}
With CSS you can transform boring HTML menus into good-looking navigation
bars.
<ul>
<li><a href="default.asp">Home</a></li>
<li><a href="news.asp">News</a></li>
<li><a href="contact.asp">Contact</a></li>
<li><a href="about.asp">About</a></li>
</ul>
Now let's remove the bullets and the margins and padding from the list:
ul {
list-style-type: none;
margin: 0;
padding: 0;}
Example explained:
The code in the example above is the standard code used in both vertical, and
horizontal navigation bars.
li a {
display: block;
width: 60px;}
Example explained:
You can also set the width of <ul>, and remove the width of <a>, as they will
take up the full width available when displayed as block elements. This will
produce the same result as our previous example.
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 200px;
background-color: #f1f1f1;}
li a {
display: block;
color: #000;
padding: 8px 16px;
text-decoration: none;}
li a.active {
background-color: #4CAF50;
color: white;}
To exclude it from hover effect Add :not(.active) like this:
li a:hover:not(.active) {
background-color: #555;
color: white;}
Add the border property to <ul> add a border around the navbar. If you also
want borders inside the navbar, add a border-bottom to all <li> elements,
except for the last one:
ul {
border: 1px solid #555;}
li {
text-align: center;
border-bottom: 1px solid #555;}
li:last-child {
border-bottom: none;}
One way to build a horizontal navigation bar is to specify the <li> elements as
inline, in addition to the "standard" code above:
li {display: inline;}
li {
float: left;}
a {
display: block;
padding: 8px;
background-color: #dddddd;}
Example explained:
float: left; - use float to get block elements to slide next to each other
display: block; - Displaying the links as block elements makes the
whole link area clickable (not just the text), and it allows us to specify
padding (and height, width, margins, etc. if you want)
padding: 8px; - Since block elements take up the full width available,
they cannot float next to each other. Therefore, specify some padding to
make them look good
background-color: #dddddd; - Add a gray background-color to each a
element
Tip: Add the background-color to <ul> instead of each <a> element if you
want a full-width background color:
ul {background-color: #dddddd;}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;}
li {float: left;}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;}
/* Change the link color to #111 (black) on hover */
li a:hover {background-color: #111;}
Right-Align Links
Right-align links by floating the list items to the right (float:right;):
Border Dividers
Add the border-right property to <li> to create link dividers:
/* Add a gray right border to all list items, except the last item (last-
child) */
li {border-right: 1px solid #bbb;}
Fixed Top
ul {
position: fixed;
top: 0;
width: 100%;}
Fixed Bottom
ul {
position: fixed;
bottom: 0;
width: 100%;}
Sticky Navbar
Add position: sticky; to <ul> to create a sticky navbar.
ul {
position: -webkit-sticky; /* Safari */
position: sticky;
top: 0;}
Note: Internet Explorer, Edge 15 and earlier versions do not support sticky
positioning. Safari requires a -webkit- prefix (see example above). You must
also specify at least one of top, right, bottom or left for sticky positioning to
work.
CSS Dropdowns:
Basic Dropdown
Create a dropdown box that appears when the user moves the mouse over an
element.
<style>
.dropdown {
position: relative;
display: inline-block;}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
z-index: 1;}
<div class="dropdown">
<span>Mouse over me</span>
<div class="dropdown-content">
<p>Hello World!</p>
</div>
</div>
Example Explained
HTML) Use any element to open the dropdown content, e.g. a <span>, or a
<button> element.
Use a container element (like <div>) to create the dropdown content and add
whatever you want inside of it.
Wrap a <div> element around the elements to position the dropdown content
correctly with CSS.
CSS) The .dropdown class uses position:relative, which is needed when we want
the dropdown content to be placed right below the dropdown button
(using position:absolute).
Instead of using a border, we have used the CSS box-shadow property to make
the dropdown menu look like a "card".
The :hover selector is used to show the dropdown menu when the user moves
the mouse over the dropdown button.
Dropdown Menu
Create a dropdown menu that allows the user to choose an option from a list:
This example is similar to the previous one, except that we add links inside the
dropdown box and style them to fit a styled dropdown button:
<style>
/* Style The Dropdown Button */
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;}
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a></div></div>
CSS Tooltip:
Create a tooltip that appears when the user moves the mouse over an element:
<style>
/* Tooltip container */
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black; /* If you want dots under the hoverable
text */}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
/* Position the tooltip text - see examples below! */
position: absolute;
z-index: 1;}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {visibility: visible;}
</style>
Positioning Tooltips
In this example, the tooltip is placed to the right (left:105%) of the "hoverable"
text (<div>). Also note that top:-5px is used to place it in the middle of its
container element. We use the number 5 because the tooltip text has a top and
bottom padding of 5px. If you increase its padding, also increase the value of
the top property to ensure that it stays in the middle (if this is something you
want). The same applies if you want the tooltip placed to the left.
Right Tooltip
.tooltip .tooltiptext {
top: -5px;
left: 105%;}
Left Tooltip
.tooltip .tooltiptext {
top: -5px;
right: 105%;}
If you want the tooltip to appear on top or on the bottom, see examples below.
Note that we use the margin-left property with a value of minus 60 pixels. This
is to center the tooltip above/below the hoverable text. It is set to the half of
the tooltip's width (120/2 = 60).
Top Tooltip
.tooltip .tooltiptext {
width: 120px;
bottom: 100%;
left: 50%;
margin-left: -60px; /* Use half of the width (120/2 = 60), to center the
tooltip */}
Bottom Tooltip
.tooltip .tooltiptext {
width: 120px;
top: 100%;
left: 50%;
margin-left: -60px; /* Use half of the width (120/2 = 60), to center the
tooltip */}
Tooltip Arrows
To create an arrow that should appear from a specific side of the tooltip, add
"empty" content after tooltip, with the pseudo-element class ::after together
with the content property. The arrow itself is created using borders. This will
make the tooltip look like a speech bubble.
This example demonstrates how to add an arrow to the bottom of the tooltip:
.tooltip .tooltiptext::after {
content: " ";
position: absolute;
top: 100%; /* At the bottom of the tooltip */
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: black transparent transparent transparent;}
Note: The border-color is used to transform the content into an arrow. We set
the top border to black, and the rest to transparent. If all sides were black, you
would end up with a black square box.
CSS Media Queries:
CSS2 Introduced Media Types
The @media rule, introduced in CSS2, made it possible to define different style
rules for different media types.
Examples: You could have one set of style rules for computer screens, one for
printers, one for handheld devices, one for television-type devices, and so on.
Unfortunately these media types never got a lot of support by devices, other
than the print media type.
Using media queries are a popular technique for delivering a tailored style sheet
to desktops, laptops, tablets, and mobile phones (such as iPhone and Android
phones).
The result of the query is true if the specified media type matches the type of
device the document is being displayed on and all expressions in the media
query are true. When a media query is true, the corresponding style sheet or
style rules are applied, following the normal cascading rules.
Unless you use the not or only operators, the media type is optional and
the all type will be implied.
The following example shows a menu that will float to the left of the page if the
viewport is 480 pixels wide or wider (if the viewport is less than 480 pixels, the
menu will be on top of the content):
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:
.header {
background-color: #F1F1F1;
text-align: center;
padding: 20px;}
Navigation Bar
A navigation bar contains a list of links to help visitors navigating through your
website.
Content
The layout in this section, often depends on the target users. The most common
layout is one (or combining them) of the following:
/* 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%;}}
Unequal Columns
The main content is the biggest and the most important part of your site.
/* 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%;}}
Footer
The footer is placed at the bottom of your page. It often contains information
like copyright and contact info:
.footer {
background-color: #F1F1F1;
text-align: center;
padding: 10px;}
CSS Specificity:
What is Specificity? If there are two or more conflicting CSS rules that point to
the same element, the browser follows some rules to determine which one is
most specific and therefore wins out.
The universal selector (*) has low specificity, while ID selectors are highly
specific!
Note: Specificity is a common reason why your CSS-rules don't apply to some
elements, although you think they should.
Specificity Hierarchy
Every selector has its place in the specificity hierarchy. There are four
categories which define the specificity level of a selector:
A: h1
B: #content h1
C: <div id="content"><h1 style="color: #ffffff">Heading</h1></div>
Since 1 < 101 < 1000, the third rule (C) has a greater level of specificity, and
therefore will be applied.
Specificity Rules
Equal specificity: the latest rule counts - If the same rule is written twice
into the external style sheet, then the lower rule in the style sheet is closer to
the element to be styled, and therefore will be applied:
h1 {background-color: yellow;}
h1 {background-color: red;}
the first rule is more specific than the other two, and will be applied.
In HTML file:
<style>
#content h1 {background-color: yellow;}
</style>