0% found this document useful (0 votes)
23 views

CSSNotesForProfessionals 1 100

Uploaded by

shivakrishna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

CSSNotesForProfessionals 1 100

Uploaded by

shivakrishna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

CSS

CSS
Notes for Professionals

Notes for Professionals

200+ pages
of professional hints and tricks

Disclaimer
GoalKicker.com This is an unocial free book created for educational purposes and is
not aliated with ocial CSS group(s) or company(s).
Free Programming Books All trademarks and registered trademarks are
the property of their respective owners
Contents
About ................................................................................................................................................................................... 1
Chapter 1: Getting started with CSS .................................................................................................................... 2
Section 1.1: External Stylesheet ..................................................................................................................................... 2
Section 1.2: Internal Styles ............................................................................................................................................ 3
Section 1.3: CSS @import rule (one of CSS at-rule) ................................................................................................... 4
Section 1.4: Inline Styles ................................................................................................................................................. 4
Section 1.5: Changing CSS with JavaScript ................................................................................................................. 4
Section 1.6: Styling Lists with CSS ................................................................................................................................. 5
Chapter 2: Structure and Formatting of a CSS Rule .................................................................................. 7
Section 2.1: Property Lists ............................................................................................................................................. 7
Section 2.2: Multiple Selectors ...................................................................................................................................... 7
Section 2.3: Rules, Selectors, and Declaration Blocks ............................................................................................... 7
Chapter 3: Comments ................................................................................................................................................. 8
Section 3.1: Single Line ................................................................................................................................................... 8
Section 3.2: Multiple Line ............................................................................................................................................... 8
Chapter 4: Selectors ................................................................................................................................................... 9
Section 4.1: Basic selectors ........................................................................................................................................... 9
Section 4.2: Attribute Selectors .................................................................................................................................... 9
Section 4.3: Combinators ............................................................................................................................................ 12
Section 4.4: Pseudo-classes ....................................................................................................................................... 13
Section 4.5: Child Pseudo Class ................................................................................................................................. 15
Section 4.6: Class Name Selectors ............................................................................................................................ 16
Section 4.7: Select element using its ID without the high specificity of the ID selector ....................................... 17
Section 4.8: The :last-of-type selector ...................................................................................................................... 17
Section 4.9: CSS3 :in-range selector example .......................................................................................................... 17
Section 4.10: A. The :not pseudo-class example & B. :focus-within CSS pseudo-class ......................................... 18
Section 4.11: Global boolean with checkbox:checked and ~ (general sibling combinator) .................................. 19
Section 4.12: ID selectors ............................................................................................................................................ 20
Section 4.13: How to style a Range input .................................................................................................................. 21
Section 4.14: The :only-child pseudo-class selector example ................................................................................. 21
Chapter 5: Backgrounds ......................................................................................................................................... 22
Section 5.1: Background Color ................................................................................................................................... 22
Section 5.2: Background Gradients ........................................................................................................................... 24
Section 5.3: Background Image ................................................................................................................................. 25
Section 5.4: Background Shorthand .......................................................................................................................... 26
Section 5.5: Background Size ..................................................................................................................................... 27
Section 5.6: Background Position .............................................................................................................................. 31
Section 5.7: The background-origin property .......................................................................................................... 32
Section 5.8: Multiple Background Image .................................................................................................................. 34
Section 5.9: Background Attachment ....................................................................................................................... 35
Section 5.10: Background Clip .................................................................................................................................... 36
Section 5.11: Background Repeat ............................................................................................................................... 37
Section 5.12: background-blend-mode Property ..................................................................................................... 37
Section 5.13: Background Color with Opacity ........................................................................................................... 38
Chapter 6: Centering ................................................................................................................................................. 39
Section 6.1: Using Flexbox ........................................................................................................................................... 39
Section 6.2: Using CSS transform .............................................................................................................................. 40
Section 6.3: Using margin: 0 auto; ............................................................................................................................. 41
Section 6.4: Using text-align ....................................................................................................................................... 42
Section 6.5: Using position: absolute ......................................................................................................................... 42
Section 6.6: Using calc() ............................................................................................................................................. 43
Section 6.7: Using line-height ..................................................................................................................................... 43
Section 6.8: Vertical align anything with 3 lines of code ......................................................................................... 44
Section 6.9: Centering in relation to another item ................................................................................................... 44
Section 6.10: Ghost element technique (Michał Czernow's hack) ........................................................................... 45
Section 6.11: Centering vertically and horizontally without worrying about height or width ............................... 46
Section 6.12: Vertically align an image inside div ..................................................................................................... 47
Section 6.13: Centering with fixed size ....................................................................................................................... 47
Section 6.14: Vertically align dynamic height elements .......................................................................................... 49
Section 6.15: Horizontal and Vertical centering using table layout ........................................................................ 49
Chapter 7: The Box Model ...................................................................................................................................... 51
Section 7.1: What is the Box Model? .......................................................................................................................... 51
Section 7.2: box-sizing ................................................................................................................................................. 52
Chapter 8: Margins .................................................................................................................................................... 55
Section 8.1: Margin Collapsing .................................................................................................................................... 55
Section 8.2: Apply Margin on a Given Side ............................................................................................................... 57
Section 8.3: Margin property simplification .............................................................................................................. 58
Section 8.4: Horizontally center elements on a page using margin ...................................................................... 58
Section 8.5: Example 1: ................................................................................................................................................ 59
Section 8.6: Negative margins ................................................................................................................................... 59
Chapter 9: Padding .................................................................................................................................................... 61
Section 9.1: Padding Shorthand ................................................................................................................................. 61
Section 9.2: Padding on a given side ........................................................................................................................ 62
Chapter 10: Border ..................................................................................................................................................... 63
Section 10.1: border-radius ......................................................................................................................................... 63
Section 10.2: border-style ........................................................................................................................................... 64
Section 10.3: Multiple Borders .................................................................................................................................... 65
Section 10.4: border (shorthands) ............................................................................................................................. 66
Section 10.5: border-collapse ..................................................................................................................................... 66
Section 10.6: border-image ........................................................................................................................................ 67
Section 10.7: Creating a multi-colored border using border-image ...................................................................... 67
Section 10.8: border-[left|right|top|bottom] .............................................................................................................. 68
Chapter 11: Outlines ................................................................................................................................................... 69
Section 11.1: Overview .................................................................................................................................................. 69
Section 11.2: outline-style ............................................................................................................................................ 69
Chapter 12: Overflow ................................................................................................................................................ 71
Section 12.1: overflow-wrap ........................................................................................................................................ 71
Section 12.2: overflow-x and overflow-y ................................................................................................................... 72
Section 12.3: overflow: scroll ....................................................................................................................................... 73
Section 12.4: overflow: visible ..................................................................................................................................... 73
Section 12.5: Block Formatting Context Created with Overflow ............................................................................. 74
Chapter 13: Media Queries ...................................................................................................................................... 76
Section 13.1: Terminology and Structure ................................................................................................................... 76
Section 13.2: Basic Example ........................................................................................................................................ 77
Section 13.3: mediatype .............................................................................................................................................. 77
Section 13.4: Media Queries for Retina and Non Retina Screens ........................................................................... 78
Section 13.5: Width vs Viewport ................................................................................................................................. 79
Section 13.6: Using Media Queries to Target Dierent Screen Sizes ..................................................................... 79
Section 13.7: Use on link tag ....................................................................................................................................... 80
Section 13.8: Media queries and IE8 ........................................................................................................................... 80
Chapter 14: Floats ...................................................................................................................................................... 81
Section 14.1: Float an Image Within Text ................................................................................................................... 81
Section 14.2: clear property ........................................................................................................................................ 82
Section 14.3: Clearfix .................................................................................................................................................... 83
Section 14.4: In-line DIV using float ............................................................................................................................ 84
Section 14.5: Use of overflow property to clear floats ............................................................................................ 86
Section 14.6: Simple Two Fixed-Width Column Layout ............................................................................................ 86
Section 14.7: Simple Three Fixed-Width Column Layout ......................................................................................... 87
Section 14.8: Two-Column Lazy/Greedy Layout ...................................................................................................... 88
Chapter 15: Typography ......................................................................................................................................... 89
Section 15.1: The Font Shorthand ............................................................................................................................... 89
Section 15.2: Quotes .................................................................................................................................................... 90
Section 15.3: Font Size ................................................................................................................................................. 90
Section 15.4: Text Direction ......................................................................................................................................... 90
Section 15.5: Font Stacks ............................................................................................................................................ 91
Section 15.6: Text Overflow ......................................................................................................................................... 91
Section 15.7: Text Shadow .......................................................................................................................................... 91
Section 15.8: Text Transform ...................................................................................................................................... 92
Section 15.9: Letter Spacing ........................................................................................................................................ 92
Section 15.10: Text Indent ............................................................................................................................................ 93
Section 15.11: Text Decoration ..................................................................................................................................... 93
Section 15.12: Word Spacing ....................................................................................................................................... 94
Section 15.13: Font Variant .......................................................................................................................................... 94
Chapter 16: Flexible Box Layout (Flexbox) ..................................................................................................... 96
Section 16.1: Dynamic Vertical and Horizontal Centering (align-items, justify-content) ...................................... 96
Section 16.2: Sticky Variable-Height Footer ........................................................................................................... 102
Section 16.3: Optimally fit elements to their container .......................................................................................... 103
Section 16.4: Holy Grail Layout using Flexbox ........................................................................................................ 104
Section 16.5: Perfectly aligned buttons inside cards with flexbox ........................................................................ 105
Section 16.6: Same height on nested containers .................................................................................................... 107
Chapter 17: Cascading and Specificity .......................................................................................................... 109
Section 17.1: Calculating Selector Specificity ........................................................................................................... 109
Section 17.2: The !important declaration ................................................................................................................. 111
Section 17.3: Cascading ............................................................................................................................................. 112
Section 17.4: More complex specificity example .................................................................................................... 113
Chapter 18: Colors .................................................................................................................................................... 115
Section 18.1: currentColor .......................................................................................................................................... 115
Section 18.2: Color Keywords ................................................................................................................................... 116
Section 18.3: Hexadecimal Value ............................................................................................................................. 122
Section 18.4: rgb() Notation ...................................................................................................................................... 122
Section 18.5: rgba() Notation ................................................................................................................................... 123
Section 18.6: hsl() Notation ....................................................................................................................................... 123
Section 18.7: hsla() Notation ..................................................................................................................................... 124
Chapter 19: Opacity ................................................................................................................................................. 126
Section 19.1: Opacity Property .................................................................................................................................. 126
Section 19.2: IE Compatibility for `opacity` .............................................................................................................. 126
Chapter 20: Length Units ...................................................................................................................................... 127
Section 20.1: Creating scalable elements using rems and ems ........................................................................... 127
Section 20.2: Font size with rem .............................................................................................................................. 128
Section 20.3: vmin and vmax ................................................................................................................................... 129
Section 20.4: vh and vw ............................................................................................................................................ 129
Section 20.5: using percent % .................................................................................................................................. 129
Chapter 21: Pseudo-Elements ............................................................................................................................. 131
Section 21.1: Pseudo-Elements ................................................................................................................................. 131
Section 21.2: Pseudo-Elements in Lists .................................................................................................................... 131
Chapter 22: Positioning .......................................................................................................................................... 133
Section 22.1: Overlapping Elements with z-index ................................................................................................... 133
Section 22.2: Absolute Position ................................................................................................................................ 134
Section 22.3: Fixed position ...................................................................................................................................... 135
Section 22.4: Relative Position ................................................................................................................................. 135
Section 22.5: Static positioning ................................................................................................................................ 135
Chapter 23: Layout Control ................................................................................................................................. 137
Section 23.1: The display property ........................................................................................................................... 137
Section 23.2: To get old table structure using div ................................................................................................. 139
Chapter 24: Grid ........................................................................................................................................................ 141
Section 24.1: Basic Example ..................................................................................................................................... 141
Chapter 25: Tables ................................................................................................................................................... 143
Section 25.1: table-layout ......................................................................................................................................... 143
Section 25.2: empty-cells ......................................................................................................................................... 143
Section 25.3: border-collapse .................................................................................................................................. 143
Section 25.4: border-spacing ................................................................................................................................... 144
Section 25.5: caption-side ........................................................................................................................................ 144
Chapter 26: Transitions ......................................................................................................................................... 145
Section 26.1: Transition shorthand ........................................................................................................................... 145
Section 26.2: cubic-bezier ......................................................................................................................................... 145
Section 26.3: Transition (longhand) ........................................................................................................................ 147
Chapter 27: Animations ......................................................................................................................................... 148
Section 27.1: Animations with keyframes ................................................................................................................ 148
Section 27.2: Animations with the transition property .......................................................................................... 149
Section 27.3: Syntax Examples ................................................................................................................................ 150
Section 27.4: Increasing Animation Performance Using the `will-change` Attribute .......................................... 151
Chapter 28: 2D Transforms ................................................................................................................................. 152
Section 28.1: Rotate ................................................................................................................................................... 152
Section 28.2: Scale .................................................................................................................................................... 153
Section 28.3: Skew ..................................................................................................................................................... 153
Section 28.4: Multiple transforms ............................................................................................................................ 153
Section 28.5: Translate ............................................................................................................................................. 154
Section 28.6: Transform Origin ................................................................................................................................ 155
Chapter 29: 3D Transforms ................................................................................................................................. 156
Section 29.1: Compass pointer or needle shape using 3D transforms ................................................................ 156
Section 29.2: 3D text eect with shadow ................................................................................................................ 157
Section 29.3: backface-visibility ............................................................................................................................... 158
Section 29.4: 3D cube ............................................................................................................................................... 159
Chapter 30: Filter Property ................................................................................................................................. 161
Section 30.1: Blur ........................................................................................................................................................ 161
Section 30.2: Drop Shadow (use box-shadow instead if possible) ...................................................................... 161
Section 30.3: Hue Rotate .......................................................................................................................................... 162
Section 30.4: Multiple Filter Values .......................................................................................................................... 162
Section 30.5: Invert Color ......................................................................................................................................... 163
Chapter 31: Cursor Styling .................................................................................................................................... 164
Section 31.1: Changing cursor type .......................................................................................................................... 164
Section 31.2: pointer-events ..................................................................................................................................... 164
Section 31.3: caret-color ............................................................................................................................................ 165
Chapter 32: box-shadow ....................................................................................................................................... 166
Section 32.1: bottom-only drop shadow using a pseudo-element ...................................................................... 166
Section 32.2: drop shadow ....................................................................................................................................... 167
Section 32.3: inner drop shadow ............................................................................................................................. 167
Section 32.4: multiple shadows ................................................................................................................................ 168
Chapter 33: Shapes for Floats ........................................................................................................................... 170
Section 33.1: Shape Outside with Basic Shape – circle() ........................................................................................ 170
Section 33.2: Shape margin ...................................................................................................................................... 171
Chapter 34: List Styles ........................................................................................................................................... 173
Section 34.1: Bullet Position ...................................................................................................................................... 173
Section 34.2: Removing Bullets / Numbers ............................................................................................................ 173
Section 34.3: Type of Bullet or Numbering ............................................................................................................. 173
Chapter 35: Counters .............................................................................................................................................. 175
Section 35.1: Applying roman numerals styling to the counter output ............................................................... 175
Section 35.2: Number each item using CSS Counter ............................................................................................. 175
Section 35.3: Implementing multi-level numbering using CSS counters ............................................................. 176
Chapter 36: Functions ............................................................................................................................................. 178
Section 36.1: calc() function ...................................................................................................................................... 178
Section 36.2: attr() function ...................................................................................................................................... 178
Section 36.3: var() function ...................................................................................................................................... 178
Section 36.4: radial-gradient() function .................................................................................................................. 179
Section 36.5: linear-gradient() function .................................................................................................................. 179
Chapter 37: Custom Properties (Variables) ................................................................................................ 180
Section 37.1: Variable Color ...................................................................................................................................... 180
Section 37.2: Variable Dimensions .......................................................................................................................... 180
Section 37.3: Variable Cascading ............................................................................................................................ 180
Section 37.4: Valid/Invalids ...................................................................................................................................... 181
Section 37.5: With media queries ............................................................................................................................. 182
Chapter 38: Single Element Shapes ................................................................................................................ 184
Section 38.1: Trapezoid ............................................................................................................................................. 184
Section 38.2: Triangles .............................................................................................................................................. 184
Section 38.3: Circles and Ellipses ............................................................................................................................. 187
Section 38.4: Bursts ................................................................................................................................................... 188
Section 38.5: Square ................................................................................................................................................. 190
Section 38.6: Cube ..................................................................................................................................................... 190
Section 38.7: Pyramid ............................................................................................................................................... 191
Chapter 39: Columns ............................................................................................................................................... 193
Section 39.1: Simple Example (column-count) ....................................................................................................... 193
Section 39.2: Column Width ..................................................................................................................................... 193
Chapter 40: Multiple columns ............................................................................................................................ 195
Section 40.1: Create Multiple Columns .................................................................................................................... 195
Section 40.2: Basic example .................................................................................................................................... 195
Chapter 41: Inline-Block Layout ........................................................................................................................ 196
Section 41.1: Justified navigation bar ...................................................................................................................... 196
Chapter 42: Inheritance ........................................................................................................................................ 197
Section 42.1: Automatic inheritance ........................................................................................................................ 197
Section 42.2: Enforced inheritance .......................................................................................................................... 197
Chapter 43: CSS Image Sprites ......................................................................................................................... 198
Section 43.1: A Basic Implementation ...................................................................................................................... 198
Chapter 44: Clipping and Masking .................................................................................................................. 199
Section 44.1: Clipping and Masking: Overview and Dierence ............................................................................. 199
Section 44.2: Simple mask that fades an image from solid to transparent ....................................................... 201
Section 44.3: Clipping (Circle) .................................................................................................................................. 201
Section 44.4: Clipping (Polygon) .............................................................................................................................. 202
Section 44.5: Using masks to cut a hole in the middle of an image .................................................................... 203
Section 44.6: Using masks to create images with irregular shapes .................................................................... 204
Chapter 45: Fragmentation ................................................................................................................................ 206
Section 45.1: Media print page-break ..................................................................................................................... 206
Chapter 46: CSS Object Model (CSSOM) ....................................................................................................... 207
Section 46.1: Adding a background-image rule via the CSSOM ........................................................................... 207
Section 46.2: Introduction ......................................................................................................................................... 207
Chapter 47: Feature Queries .............................................................................................................................. 208
Section 47.1: Basic @supports usage ...................................................................................................................... 208
Section 47.2: Chaining feature detections .............................................................................................................. 208
Chapter 48: Stacking Context ........................................................................................................................... 209
Section 48.1: Stacking Context ................................................................................................................................. 209
Chapter 49: Block Formatting Contexts ....................................................................................................... 212
Section 49.1: Using the overflow property with a value dierent to visible ........................................................ 212
Chapter 50: Vertical Centering .......................................................................................................................... 213
Section 50.1: Centering with display: table .............................................................................................................. 213
Section 50.2: Centering with Flexbox ...................................................................................................................... 213
Section 50.3: Centering with Transform ................................................................................................................. 214
Section 50.4: Centering Text with Line Height ........................................................................................................ 214
Section 50.5: Centering with Position: absolute ..................................................................................................... 214
Section 50.6: Centering with pseudo element ........................................................................................................ 215
Chapter 51: Object Fit and Placement ........................................................................................................... 217
Section 51.1: object-fit ................................................................................................................................................ 217
Chapter 52: CSS design patterns ..................................................................................................................... 220
Section 52.1: BEM ....................................................................................................................................................... 220
Chapter 53: Browser Support & Prefixes ...................................................................................................... 222
Section 53.1: Transitions ............................................................................................................................................ 222
Section 53.2: Transform ........................................................................................................................................... 222
Chapter 54: Normalizing Browser Styles ..................................................................................................... 223
Section 54.1: normalize.css ....................................................................................................................................... 223
Section 54.2: Approaches and Examples ............................................................................................................... 223
Chapter 55: Internet Explorer Hacks .............................................................................................................. 226
Section 55.1: Adding Inline Block support to IE6 and IE7 ....................................................................................... 226
Section 55.2: High Contrast Mode in Internet Explorer 10 and greater ............................................................... 226
Section 55.3: Internet Explorer 6 & Internet Explorer 7 only ................................................................................. 227
Section 55.4: Internet Explorer 8 only ..................................................................................................................... 227
Chapter 56: Performance ..................................................................................................................................... 228
Section 56.1: Use transform and opacity to avoid trigger layout ........................................................................ 228
Credits ............................................................................................................................................................................ 231
You may also like ...................................................................................................................................................... 236
About

Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
https://goalkicker.com/CSSBook

This CSS Notes for Professionals book is compiled from Stack Overflow
Documentation, the content is written by the beautiful people at Stack Overflow.
Text content is released under Creative Commons BY-SA, see credits at the end
of this book whom contributed to the various chapters. Images may be copyright
of their respective owners unless otherwise specified

This is an unofficial free book created for educational purposes and is not
affiliated with official CSS group(s) or company(s) nor Stack Overflow. All
trademarks and registered trademarks are the property of their respective
company owners

The information presented in this book is not guaranteed to be correct nor


accurate, use at your own risk

Please send feedback and corrections to web@petercv.com

GoalKicker.com – CSS Notes for Professionals 1


Chapter 1: Getting started with CSS
Version Release Date
1 1996-12-17
2 1998-05-12
3 2015-10-13

Section 1.1: External Stylesheet


An external CSS stylesheet can be applied to any number of HTML documents by placing a <link> element in each
HTML document.

The attribute rel of the <link> tag has to be set to "stylesheet", and the href attribute to the relative or absolute
path to the stylesheet. While using relative URL paths is generally considered good practice, absolute paths can be
used, too. In HTML5 the type attribute can be omitted.

It is recommended that the <link> tag be placed in the HTML file's <head> tag so that the styles are loaded before
the elements they style. Otherwise, users will see a flash of unstyled content.

Example

hello-world.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Hello world!</h1>
<p>I ♥ CSS</p>
</body>
</html>

style.css

h1 {
color: green;
text-decoration: underline;
}
p {
font-size: 25px;
font-family: 'Trebuchet MS', sans-serif;
}

Make sure you include the correct path to your CSS file in the href. If the CSS file is in the same folder as your HTML
file then no path is required (like the example above) but if it's saved in a folder, then specify it like this
href="foldername/style.css".

<link rel="stylesheet" type="text/css" href="foldername/style.css">

External stylesheets are considered the best way to handle your CSS. There's a very simple reason for this: when
you're managing a site of, say, 100 pages, all controlled by a single stylesheet, and you want to change your link

GoalKicker.com – CSS Notes for Professionals 2


colors from blue to green, it's a lot easier to make the change in your CSS file and let the changes "cascade"
throughout all 100 pages than it is to go into 100 separate pages and make the same change 100 times. Again, if
you want to completely change the look of your website, you only need to update this one file.

You can load as many CSS files in your HTML page as needed.

<link rel="stylesheet" type="text/css" href="main.css">


<link rel="stylesheet" type="text/css" href="override.css">

CSS rules are applied with some basic rules, and order does matter. For example, if you have a main.css file with
some code in it:

p.green { color: #00FF00; }

All your paragraphs with the 'green' class will be written in light green, but you can override this with another .css
file just by including it after main.css. You can have override.css with the following code follow main.css, for
example:

p.green { color: #006600; }

Now all your paragraphs with the 'green' class will be written in darker green rather than light green.

Other principles apply, such as the '!important' rule, specificity, and inheritance.

When someone first visits your website, their browser downloads the HTML of the current page plus the linked CSS
file. Then when they navigate to another page, their browser only needs to download the HTML of that page; the
CSS file is cached, so it does not need to be downloaded again. Since browsers cache the external stylesheet, your
pages load faster.

Section 1.2: Internal Styles


CSS enclosed in <style></style> tags within an HTML document functions like an external stylesheet, except that
it lives in the HTML document it styles instead of in a separate file, and therefore can only be applied to the
document in which it lives. Note that this element must be inside the <head> element for HTML validation (though it
will work in all current browsers if placed in body).

<head>
<style>
h1 {
color: green;
text-decoration: underline;
}
p {
font-size: 25px;
font-family: 'Trebuchet MS', sans-serif;
}
</style>
</head>
<body>
<h1>Hello world!</h1>
<p>I ♥ CSS</p>
</body>

GoalKicker.com – CSS Notes for Professionals 3


Section 1.3: CSS @import rule (one of CSS at-rule)
The @import CSS at-rule is used to import style rules from other style sheets. These rules must precede all other
types of rules, except @charset rules; as it is not a nested statement, @import cannot be used inside conditional
group at-rules. @import.

How to use @import

You can use @import rule in following ways:

A. With internal style tag

<style>
@import url('/css/styles.css');
</style>

B. With external stylesheet

The following line imports a CSS file named additional-styles.css in the root directory into the CSS file in which it
appears:

@import '/additional-styles.css';

Importing external CSS is also possible. A common use case are font files.

@import 'https://fonts.googleapis.com/css?family=Lato';

An optional second argument to @import rule is a list of media queries:

@import '/print-styles.css' print;


@import url('landscape.css') screen and (orientation:landscape);

Section 1.4: Inline Styles


Use inline styles to apply styling to a specific element. Note that this is not optimal. Placing style rules in a <style>
tag or external CSS file is encouraged in order to maintain a distinction between content and presentation.

Inline styles override any CSS in a <style> tag or external style sheet. While this can be useful in some
circumstances, this fact more often than not reduces a project's maintainability.

The styles in the following example apply directly to the elements to which they are attached.

<h1 style="color: green; text-decoration: underline;">Hello world!</h1>


<p style="font-size: 25px; font-family: 'Trebuchet MS';">I ♥ CSS</p>

Inline styles are generally the safest way to ensure rendering compatibility across various email clients, programs
and devices, but can be time-consuming to write and a bit challenging to manage.

Section 1.5: Changing CSS with JavaScript


Pure JavaScript

It's possible to add, remove or change CSS property values with JavaScript through an element's style property.

GoalKicker.com – CSS Notes for Professionals 4


var el = document.getElementById("element");
el.style.opacity = 0.5;
el.style.fontFamily = 'sans-serif';

Note that style properties are named in lower camel case style. In the example you see that the css property font-
family becomes fontFamily in javascript.

As an alternative to working directly on elements, you can create a <style> or <link> element in JavaScript and
append it to the <body> or <head> of the HTML document.

jQuery

Modifying CSS properties with jQuery is even simpler.

$('#element').css('margin', '5px');

If you need to change more than one style rule:

$('#element').css({
margin: "5px",
padding: "10px",
color: "black"
});

jQuery includes two ways to change css rules that have hyphens in them (i.e. font-size). You can put them in
quotes or camel-case the style rule name.

$('.example-class').css({
"background-color": "blue",
fontSize: "10px"
});

See also

JavaScript documentation – Reading and Changing CSS Style.


jQuery documentation – CSS Manipulation

Section 1.6: Styling Lists with CSS


There are three different properties for styling list-items: list-style-type, list-style-image, and list-style-
position, which should be declared in that order. The default values are disc, outside, and none, respectively. Each
property can be declared separately, or using the list-style shorthand property.

list-style-type defines the shape or type of bullet point used for each list-item.

Some of the acceptable values for list-style-type:

disc
circle
square
decimal
lower-roman
upper-roman
none

(For an exhaustive list, see the W3C specification wiki)

GoalKicker.com – CSS Notes for Professionals 5


To use square bullet points for each list-item, for example, you would use the following property-value pair:

li {
list-style-type: square;
}

The list-style-image property determines whether the list-item icon is set with an image, and accepts a value of
none or a URL that points to an image.

li {
list-style-image: url(images/bullet.png);
}

The list-style-position property defines where to position the list-item marker, and it accepts one of two values:
"inside" or "outside".

li {
list-style-position: inside;
}

GoalKicker.com – CSS Notes for Professionals 6


Chapter 2: Structure and Formatting of a
CSS Rule
Section 2.1: Property Lists
Some properties can take multiple values, collectively known as a property list.

/* Two values in this property list */


span {
text-shadow: yellow 0 0 3px, green 4px 4px 10px;
}

/* Alternate Formatting */
span {
text-shadow:
yellow 0 0 3px,
green 4px 4px 10px;
}

Section 2.2: Multiple Selectors


When you group CSS selectors, you apply the same styles to several different elements without repeating the styles
in your style sheet. Use a comma to separate multiple grouped selectors.

div, p { color: blue }

So the blue color applies to all <div> elements and all <p> elements. Without the comma only <p> elements that are
a child of a <div> would be red.

This also applies to all types of selectors.

p, .blue, #first, div span{ color : blue }

This rule applies to:

<p>
elements of the blue class
element with the ID first
every <span> inside of a <div>

Section 2.3: Rules, Selectors, and Declaration Blocks


A CSS rule consists of a selector (e.g. h1) and declaration block ({}).

h1 {}

GoalKicker.com – CSS Notes for Professionals 7


Chapter 3: Comments
Section 3.1: Single Line
/* This is a CSS comment */
div {
color: red; /* This is a CSS comment */
}

Section 3.2: Multiple Line


/*
This
is
a
CSS
comment
*/
div {
color: red;
}

GoalKicker.com – CSS Notes for Professionals 8


Chapter 4: Selectors
CSS selectors identify specific HTML elements as targets for CSS styles. This topic covers how CSS selectors target
HTML elements. Selectors use a wide range of over 50 selection methods offered by the CSS language, including
elements, classes, IDs, pseudo-elements and pseudo-classes, and patterns.

Section 4.1: Basic selectors


Selector Description
* Universal selector (all elements)
div Tag selector (all <div> elements)
.blue Class selector (all elements with class blue)
.blue.red All elements with class blue and red (a type of Compound selector)
#headline ID selector (the element with "id" attribute set to headline)
:pseudo-class All elements with pseudo-class
::pseudo-element Element that matches pseudo-element
:lang(en) Element that matches :lang declaration, for example <span lang="en">
div > p child selector

Note: The value of an ID must be unique in a web page. It is a violation of the HTML standard to use the
value of an ID more than once in the same document tree.

A complete list of selectors can be found in the CSS Selectors Level 3 specification.

Section 4.2: Attribute Selectors


Overview

Attribute selectors can be used with various types of operators that change the selection criteria accordingly. They
select an element using the presence of a given attribute or attribute value.

Selector(1) Matched element Selects elements... CSS Version


[attr] <div attr> With attribute attr 2
[attr='val'] <div attr="val"> Where attribute attr has value val 2
Where val appears in the
[attr~='val'] <div attr="val val2 val3"> 2
whitespace-separated list of attr
[attr^='val'] <div attr="val1 val2"> Where attr's value begins with val 3
[attr$='val'] <div attr="sth aval"> Where the attr's value ends with val 3
[attr*='val'] <div attr="somevalhere"> Where attr contains val anywhere 3
Where attr's value is exactly val,
[attr|='val'] <div attr="val-sth etc"> or starts with val and immediately 2
followed by - (U+002D)
Where attr has value val,
[attr='val' i] <div attr="val"> 4(2)
ignoring val's letter casing.

Notes:

1. The attribute value can be surrounded by either single-quotes or double-quotes. No quotes at all may also
work, but it's not valid according to the CSS standard, and is discouraged.

GoalKicker.com – CSS Notes for Professionals 9


2. There is no single, integrated CSS4 specification, because it is split into separate modules. However, there are
"level 4" modules. See browser support.

Details
[attribute]

Selects elements with the given attribute.

div[data-color] {
color: red;
}

<div data-color="red">This will be red</div>


<div data-color="green">This will be red</div>
<div data-background="red">This will NOT be red</div>

Live Demo on JSBin

[attribute="value"]

Selects elements with the given attribute and value.

div[data-color="red"] {
color: red;
}

<div data-color="red">This will be red</div>


<div data-color="green">This will NOT be red</div>
<div data-color="blue">This will NOT be red</div>

Live Demo on JSBin

[attribute*="value"]

Selects elements with the given attribute and value where the given attribute contains the given value anywhere (as
a substring).

[class*="foo"] {
color: red;
}

<div class="foo-123">This will be red</div>


<div class="foo123">This will be red</div>
<div class="bar123foo">This will be red</div>
<div class="barfooo123">This will be red</div>
<div class="barfo0">This will NOT be red</div>

Live Demo on JSBin

[attribute~="value"]

Selects elements with the given attribute and value where the given value appears in a whitespace-separated list.

[class~="color-red"] {
color: red;
}

<div class="color-red foo-bar the-div">This will be red</div>


<div class="color-blue foo-bar the-div">This will NOT be red</div>

GoalKicker.com – CSS Notes for Professionals 10


Live Demo on JSBin

[attribute^="value"]

Selects elements with the given attribute and value where the given attribute begins with the value.

[class^="foo-"] {
color: red;
}

<div class="foo-123">This will be red</div>


<div class="foo-234">This will be red</div>
<div class="bar-123">This will NOT be red</div>

Live Demo on JSBin

[attribute$="value"]

Selects elements with the given attribute and value where the given attribute ends with the given value.

[class$="file"] {
color: red;
}

<div class="foobar-file">This will be red</div>


<div class="foobar-file">This will be red</div>
<div class="foobar-input">This will NOT be red</div>

Live Demo on JSBin

[attribute|="value"]

Selects elements with a given attribute and value where the attribute's value is exactly the given value or is exactly
the given value followed by - (U+002D)

[lang|="EN"] {
color: red;
}

<div lang="EN-us">This will be red</div>


<div lang="EN-gb">This will be red</div>
<div lang="PT-pt">This will NOT be red</div>

Live Demo on JSBin

[attribute="value" i]

Selects elements with a given attribute and value where the attribute's value can be represented as Value, VALUE,
vAlUe or any other case-insensitive possibility.

[lang="EN" i] {
color: red;
}

<div lang="EN">This will be red</div>


<div lang="en">This will be red</div>
<div lang="PT">This will NOT be red</div>

Live Demo on JSBin

GoalKicker.com – CSS Notes for Professionals 11


Specificity of attribute selectors
0-1-0

Same as class selector and pseudoclass.

*[type=checkbox] // 0-1-0

Note that this means an attribute selector can be used to select an element by its ID at a lower level of specificity
than if it was selected with an ID selector: [id="my-ID"] targets the same element as #my-ID but with lower
specificity.

See the Syntax Section for more details.

Section 4.3: Combinators


Overview
Selector Description
div span Descendant selector (all <span>s that are descendants of a <div>)
div > span Child selector (all <span>s that are a direct child of a <div>)
a ~ span General Sibling selector (all <span>s that are siblings after an <a>)
a + span Adjacent Sibling selector (all <span>s that are immediately after an <a>)

Note: Sibling selectors target elements that come after them in the source document. CSS, by its nature
(it cascades), cannot target previous or parent elements. However, using the flex order property, a
previous sibling selector can be simulated on visual media.

Descendant Combinator: selector selector

A descendant combinator, represented by at least one space character (), selects elements that are a descendant of
the defined element. This combinator selects all descendants of the element (from child elements on down).

div p {
color:red;
}

<div>
<p>My text is red</p>
<section>
<p>My text is red</p>
</section>
</div>

<p>My text is not red</p>

Live Demo on JSBin

In the above example, the first two <p> elements are selected since they are both descendants of the <div>.

Child Combinator: selector > selector

The child (>) combinator is used to select elements that are children, or direct descendants, of the specified
element.

GoalKicker.com – CSS Notes for Professionals 12


div > p {
color:red;
}

<div>
<p>My text is red</p>
<section>
<p>My text is not red</p>
</section>
</div>

Live Demo on JSBin

The above CSS selects only the first <p> element, as it is the only paragraph directly descended from a <div>.

The second <p> element is not selected because it is not a direct child of the <div>.

Adjacent Sibling Combinator: selector + selector

The adjacent sibling (+) combinator selects a sibling element that immediate follows a specified element.

p + p {
color:red;
}

<p>My text is not red</p>


<p>My text is red</p>
<p>My text is red</p>
<hr>
<p>My text is not red</p>

Live Demo on JSBin

The above example selects only those <p> elements which are directly preceded by another <p> element.

General Sibling Combinator: selector ~ selector

The general sibling (~) combinator selects all siblings that follow the specified element.

p ~ p {
color:red;
}

<p>My text is not red</p>


<p>My text is red</p>
<hr>
<h1>And now a title</h1>
<p>My text is red</p>

Live Demo on JSBin

The above example selects all <p> elements that are preceded by another <p> element, whether or not they are
immediately adjacent.

Section 4.4: Pseudo-classes


Pseudo-classes are keywords which allow selection based on information that lies outside of the document tree or

GoalKicker.com – CSS Notes for Professionals 13


that cannot be expressed by other selectors or combinators. This information can be associated to a certain state
(state and dynamic pseudo-classes), to locations (structural and target pseudo-classes), to negations of the former
(negation pseudo-class) or to languages (lang pseudo-class). Examples include whether or not a link has been
followed (:visited), the mouse is over an element (:hover), a checkbox is checked (:checked), etc.

Syntax
selector:pseudo-class {
property: VALUE;
}

List of pseudo-classes:
Name Description
:active Applies to any element being activated (i.e. clicked) by the user.
Allows you to build sets of related selectors by creating groups that the
:any
included items will match. This is an alternative to repeating an entire selector.
Selects the current active #news element (clicked on a URL
:target
containing that anchor name)
Applies to radio, checkbox, or option elements that are checked
:checked
or toggled into an "on" state.
Represents any user interface element that is the default among a group of
:default
similar elements.
:disabled Applies to any UI element which is in a disabled state.
:empty Applies to any element which has no children.
:enabled Applies to any UI element which is in an enabled state.
Used in conjunction with the @page rule, this selects the first page in a
:first
printed document.
:first-child Represents any element that is the first child element of its parent.
Applies when an element is the first of the selected element type
:first-of-type
inside its parent. This may or may not be the first-child.
Applies to any element which has the user's focus. This can be given by the
:focus
user's keyboard, mouse events, or other forms of input.
Can be used to highlight a whole section when one element inside it is focused. It matches
:focus-within
any element that the :focus pseudo-class matches or that has a descendant focused.
Applies to any element displayed in full-screen mode. It selects the whole stack
:full-screen
of elements and not just the top level element.
Applies to any element being hovered by the user's pointing device, but
:hover
not activated.
Applies radio or checkbox UI elements which are neither checked nor
:indeterminate unchecked, but are in an indeterminate state. This can be due to an
element's attribute or DOM manipulation.
The :in-range CSS pseudo-class matches when an element has
its value attribute inside the specified range limitations for this element.
:in-range
It allows the page to give a feedback that the value currently defined
using the element is inside the range limits.
Applies to <input> elements whose values are invalid according to
:invalid
the type specified in the type= attribute.
Applies to any element who's wrapping <body> element has a properly
:lang designated lang= attribute. For the pseudo-class to be valid, it must
contain a valid two or three letter language code.
:last-child Represents any element that is the last child element of its parent.
Applies when an element is the last of the selected element type inside
:last-of-type
its parent. This may or may not be the last-child.

GoalKicker.com – CSS Notes for Professionals 14


Used in conjunction with the @page rule, this selects all the left
:left
pages in a printed document.
:link Applies to any links which haven't been visited by the user.
Applies to all elements which do not match the value passed to
(:not(p) or :not(.class-name) for example. It must have a value to be
:not()
valid and it can only contain one selector. However, you can chain multiple :not selectors
together.
Applies when an element is the n-th element of its parent, where n
:nth-child can be an integer, a mathematical expression (e.g n+3) or the keywords
odd or even.
Applies when an element is the n-th element of its parent of the
:nth-of-type same element type, where n can be an integer, a mathematical
expression (e.g n+3) or the keywords odd or even.
The :only-child CSS pseudo-class represents any element
which is the only child of its parent. This is the same as
:only-child
:first-child:last-child or :nth-child(1):nth-last-child(1),
but with a lower specificity.
The :optional CSS pseudo-class represents any element
:optional that does not have the required attribute set on it. This allows
forms to easily indicate optional fields and to style them accordingly.
The :out-of-range CSS pseudo-class matches when an element has its
value attribute outside the specified range limitations for this element.
:out-of-range It allows the page to give a feedback that the value currently defined using the
element is outside the range limits. A value can be outside of a range if it is
either smaller or larger than maximum and minimum set values.
:placeholder-shown Experimental. Applies to any form element currently displaying placeholder text.
:read-only Applies to any element which is not editable by the user.
:read-write Applies to any element that is editable by a user, such as <input> elements.
Used in conjunction with the @page rule, this selects all the right pages in a
:right
printed document.
:root matches the root element of a tree representing the document.
CSS pseudo-class matches the elements that are a reference
:scope
point for selectors to match against.
Selects the current active #news element (clicked on a URL
:target
containing that anchor name)
:visited Applies to any links which have has been visited by the user.

The :visited pseudoclass can't be used for most styling in a lot of modern browsers anymore because
it's a security hole. See this link for reference.

Section 4.5: Child Pseudo Class

"The :nth-child(an+b) CSS pseudo-class matches an element that has an+b-1 siblings before it in the
document tree, for a given positive or zero value for n" - MDN :nth-child

pseudo-selector 1 2 3 4 5 6 7 8 9 10
:first-child ✔
:nth-child(3) ✔
:nth-child(n+3) ✔✔✔✔✔✔✔✔
:nth-child(3n) ✔ ✔ ✔

GoalKicker.com – CSS Notes for Professionals 15


:nth-child(3n+1) ✔ ✔ ✔ ✔
:nth-child(-n+3) ✔✔✔
:nth-child(odd) ✔ ✔ ✔ ✔ ✔
:nth-child(even) ✔ ✔ ✔ ✔ ✔
:last-child ✔
:nth-last-child(3) ✔

Section 4.6: Class Name Selectors


The class name selector select all elements with the targeted class name. For example, the class name .warning
would select the following <div> element:

<div class="warning">
<p>This would be some warning copy.</p>
</div>

You can also combine class names to target elements more specifically. Let's build on the example above to
showcase a more complicated class selection.

CSS

.important {
color: orange;
}
.warning {
color: blue;
}
.warning.important {
color: red;
}

HTML

<div class="warning">
<p>This would be some warning copy.</p>
</div>

<div class="important warning">


<p class="important">This is some really important warning copy.</p>
</div>

In this example, all elements with the .warning class will have a blue text color, elements with the .important class
with have an orange text color, and all elements that have both the .important and .warning class name will have a
red text color.

Notice that within the CSS, the .warning.important declaration did not have any spaces between the two class
names. This means it will only find elements which contain both class names warning and important in their class
attribute. Those class names could be in any order on the element.

If a space was included between the two classes in the CSS declaration, it would only select elements that have
parent elements with a .warning class names and child elements with .important class names.

GoalKicker.com – CSS Notes for Professionals 16


Section 4.7: Select element using its ID without the high
specificity of the ID selector
This trick helps you select an element using the ID as a value for an attribute selector to avoid the high specificity of
the ID selector.

HTML:

<div id="element">...</div>

CSS

#element { ... } /* High specificity will override many selectors */

[id="element"] { ... } /* Low specificity, can be overridden easily */

Section 4.8: The :last-of-type selector


The :last-of-type selects the element that is the last child, of a particular type, of its parent. In the example below,
the css selects the last paragraph and the last heading h1.

p:last-of-type {
background: #C5CAE9;
}
h1:last-of-type {
background: #CDDC39;
}

<div class="container">
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Last paragraph</p>
<h1>Heading 1</h1>
<h2>First heading 2</h2>
<h2>Last heading 2</h2>
</div>

jsFiddle

Section 4.9: CSS3 :in-range selector example


<style>
input:in-range {
border: 1px solid blue;
}
</style>

<input type="number" min="10" max="20" value="15">

GoalKicker.com – CSS Notes for Professionals 17


<p>The border for this value will be blue</p>

The :in-range CSS pseudo-class matches when an element has its value attribute inside the specified range
limitations for this element. It allows the page to give a feedback that the value currently defined using the element
is inside the range limits.[1]

Section 4.10: A. The :not pseudo-class example & B. :focus-


within CSS pseudo-class
A. The syntax is presented above.

The following selector matches all <input> elements in an HTML document that are not disabled and don't have the
class .example:

HTML:

<form>
Phone: <input type="tel" class="example">
E-mail: <input type="email" disabled="disabled">
Password: <input type="password">
</form>

CSS:

input:not([disabled]):not(.example){
background-color: #ccc;
}

The :not() pseudo-class will also support comma-separated selectors in Selectors Level 4:

CSS:

input:not([disabled], .example){
background-color: #ccc;
}

Live Demo on JSBin

See background syntax here.

B. The :focus-within CSS pseudo-class

HTML:

<h3>Background is blue if the input is focused .</p>


<div>
<input type="text">
</div>

CSS:

div {
height: 80px;
}
input{
margin:30px;

GoalKicker.com – CSS Notes for Professionals 18


}
div:focus-within {
background-color: #1565C0;
}

Section 4.11: Global boolean with checkbox:checked and ~


(general sibling combinator)
With the ~ selector, you can easily implement a global accessible boolean without using JavaScript.

Add boolean as a checkbox

To the very beginning of your document, add as much booleans as you want with a unique id and the hidden
attribute set:

<input type="checkbox" id="sidebarShown" hidden />


<input type="checkbox" id="darkThemeUsed" hidden />

<!-- here begins actual content, for example: -->


<div id="container">
<div id="sidebar">
<!-- Menu, Search, ... -->
</div>

<!-- Some more content ... -->


</div>

<div id="footer">
<!-- ... -->
</div>

GoalKicker.com – CSS Notes for Professionals 19


Change the boolean's value

You can toggle the boolean by adding a label with the for attribute set:

<label for="sidebarShown">Show/Hide the sidebar!</label>

Accessing boolean value with CSS

The normal selector (like .color-red) specifies the default properties. They can be overridden by following true /
false selectors:

/* true: */
<checkbox>:checked ~ [sibling of checkbox & parent of target] <target>

/* false: */
<checkbox>:not(:checked) ~ [sibling of checkbox & parent of target] <target>

Note that <checkbox>, [sibling ...] and <target> should be replaced by the proper selectors. [sibling ...]
can be a specific selector, (often if you're lazy) simply * or nothing if the target is already a sibling of the checkbox.

Examples for the above HTML structure would be:

#sidebarShown:checked ~ #container #sidebar {


margin-left: 300px;
}

#darkThemeUsed:checked ~ #container,
#darkThemeUsed:checked ~ #footer {
background: #333;
}

In action

See this fiddle for a implementation of these global booleans.

Section 4.12: ID selectors


ID selectors select DOM elements with the targeted ID. To select an element by a specific ID in CSS, the # prefix is
used.

For example, the following HTML div element…

<div id="exampleID">
<p>Example</p>
</div>

…can be selected by #exampleID in CSS as shown below:

#exampleID {
width: 20px;
}

Note: The HTML specs do not allow multiple elements with the same ID

GoalKicker.com – CSS Notes for Professionals 20


Section 4.13: How to style a Range input
HTML

<input type="range"></input>

CSS

Effect Pseudo Selector


input[type=range]::-webkit-slider-thumb, input[type=range]::-moz-range-thumb,
Thumb input[type=range]::-ms-thumb
input[type=range]::-webkit-slider-runnable-track, input[type=range]::-moz-range-track,
Track input[type=range]::-ms-track
OnFocus input[type=range]:focus
Lower part of input[type=range]::-moz-range-progress, input[type=range]::-ms-fill-lower (not possible
the track in WebKit browsers currently - JS needed)

Section 4.14: The :only-child pseudo-class selector example


The :only-child CSS pseudo-class represents any element which is the only child of its parent.

HTML:

<div>
<p>This paragraph is the only child of the div, it will have the color blue</p>
</div>

<div>
<p>This paragraph is one of the two children of the div</p>
<p>This paragraph is one of the two children of its parent</p>
</div>

CSS:

p:only-child {
color: blue;
}

The above example selects the <p> element that is the unique child from its parent, in this case a <div>.

Live Demo on JSBin

GoalKicker.com – CSS Notes for Professionals 21


Chapter 5: Backgrounds
With CSS you can set colors, gradients, and images as the background of an element.

It is possible to specify various combinations of images, colors, and gradients, and adjust the size, positioning, and
repetition (among others) of these.

Section 5.1: Background Color


The background-color property sets the background color of an element using a color value or through keywords,
such as transparent, inherit or initial.

transparent, specifies that the background color should be transparent. This is default.

inherit, inherits this property from its parent element.

initial, sets this property to its default value.

This can be applied to all elements, and ::first-letter/::first-line pseudo-elements.

Colors in CSS can be specified by different methods.

Color names

CSS

div {
background-color: red; /* red */
}

HTML

<div>This will have a red background</div>

The example used above is one of several ways that CSS has to represent a single color.

Hex color codes

Hex code is used to denote RGB components of a color in base-16 hexadecimal notation. #ff0000, for example, is
bright red, where the red component of the color is 256 bits (ff) and the corresponding green and blue portions of
the color is 0 (00).

If both values in each of the three RGB pairings (R, G, and B) are the same, then the color code can be shortened
into three characters (the first digit of each pairing). #ff0000 can be shortened to #f00, and #ffffff can be
shortened to #fff.

Hex notation is case-insensitive.

body {
background-color: #de1205; /* red */
}

.main {

GoalKicker.com – CSS Notes for Professionals 22


background-color: #00f; /* blue */
}

RGB / RGBa

Another way to declare a color is to use RGB or RGBa.

RGB stands for Red, Green and Blue, and requires of three separate values between 0 and 255, put between
brackets, that correspond with the decimal color values for respectively red, green and blue.

RGBa allows you to add an additional alpha parameter between 0.0 and 1.0 to define opacity.

header {
background-color: rgb(0, 0, 0); /* black */
}

footer {
background-color: rgba(0, 0, 0, 0.5); /* black with 50% opacity */
}

HSL / HSLa

Another way to declare a color is to use HSL or HSLa and is similar to RGB and RGBa.

HSL stands for hue, saturation, and lightness, and is also often called HLS:

Hue is a degree on the color wheel (from 0 to 360).


Saturation is a percentage between 0% and 100%.
Lightness is also a percentage between 0% and 100%.

HSLa allows you to add an additional alpha parameter between 0.0 and 1.0 to define opacity.

li a {
background-color: hsl(120, 100%, 50%); /* green */
}

#p1 {
background-color: hsla(120, 100%, 50%, .3); /* green with 30% opacity */
}

Interaction with background-image

The following statements are all equivalent:

body {
background: red;
background-image: url(partiallytransparentimage.png);
}

body {
background-color: red;
background-image: url(partiallytransparentimage.png);
}

body {
background-image: url(partiallytransparentimage.png);
background-color: red;

GoalKicker.com – CSS Notes for Professionals 23


}

body {
background: red url(partiallytransparentimage.png);
}

They will all lead to the red color being shown underneath the image, where the parts of the image are transparent,
or the image is not showing (perhaps as a result of background-repeat).

Note that the following is not equivalent:

body {
background-image: url(partiallytransparentimage.png);
background: red;
}

Here, the value of background overrides your background-image.

For more info on the background property, see Background Shorthand

Section 5.2: Background Gradients


Gradients are new image types, added in CSS3. As an image, gradients are set with the background-image property,
or the background shorthand.

There are two types of gradient functions, linear and radial. Each type has a non-repeating variant and a repeating
variant:

linear-gradient()
repeating-linear-gradient()
radial-gradient()
repeating-radial-gradient()

linear-gradient()

A linear-gradient has the following syntax

background: linear-gradient( <direction>?, <color-stop-1>, <color-stop-2>, ...);


Value Meaning
Could be an argument like to top, to bottom, to right or to left; or an angle as 0deg,
<direction> 90deg... . The angle starts from to top and rotates clockwise. Can be specified in deg, grad, rad,
or turn. If omitted, the gradient flows from top to bottom
List of colors, optionally followed each one by a percentage or length to display it at. For
<color-stop-list>
example, yellow 10%, rgba(0,0,0,.5) 40px, #fff 100%...

For example, this creates a linear gradient that starts from the right and transitions from red to blue

.linear-gradient {
background: linear-gradient(to left, red, blue); /* you can also use 270deg */
}

You can create a diagonal gradient by declaring both a horizontal and vertical starting position.

.diagonal-linear-gradient {
background: linear-gradient(to left top, red, yellow 10%);

GoalKicker.com – CSS Notes for Professionals 24


}

It is possible to specify any number of color stops in a gradient by separating them with commas. The following
examples will create a gradient with 8 color stops

.linear-gradient-rainbow {
background: linear-gradient(to left, red, orange, yellow, green, blue, indigo, violet)
}

radial-gradient()
.radial-gradient-simple {
background: radial-gradient(red, blue);
}

.radial-gradient {
background: radial-gradient(circle farthest-corner at top left, red, blue);
}
Value Meaning
circle Shape of gradient. Values are circle or ellipse, default is ellipse.
Keywords describing how big the ending shape must be. Values are closest-side, farthest-
farthest-corner
side, closest-corner, farthest-corner
top left Sets the position of the gradient center, in the same way as background-position.

Repeating gradients

Repeating gradient functions take the same arguments as the above examples, but tile the gradient across the
background of the element.

.bullseye {
background: repeating-radial-gradient(red, red 10%, white 10%, white 20%);
}
.warning {
background: repeating-linear-gradient(-45deg, yellow, yellow 10%, black 10%, black 20% );
}
Value Meaning
Angle unit. The angle starts from to top and rotates clockwise. Can be specified in deg, grad, rad, or
-45deg
turn.
Direction of gradient, default is to bottom. Syntax: to [y-axis(top OR bottom)] [x-axis(left OR
to left
right)] ie to top right
yellow 10% Color, optionally followed by a percentage or length to display it at. Repeated two or more times.

Note that HEX, RGB, RGBa, HSL, and HSLa color codes may be used instead of color names. Color names were used
for the sake of illustration. Also note that the radial-gradient syntax is much more complex than linear-gradient,
and a simplified version is shown here. For a full explanation and specs, see the MDN Docs

Section 5.3: Background Image


The background-image property is used to specify a background image to be applied to all matched elements. By
default, this image is tiled to cover the entire element, excluding margin.

.myClass {
background-image: url('/path/to/image.jpg');
}

GoalKicker.com – CSS Notes for Professionals 25


To use multiple images as background-image, define comma separated url()

.myClass {
background-image: url('/path/to/image.jpg'),
url('/path/to/image2.jpg');
}

The images will stack according to their order with the first declared image on top of the others and so on.

Value Result
Specify background image's path(s) or an image resource specified with data URI
url('/path/to/image.jpg')
schema (apostrophes can be omitted), separate multiples by comma
none No background image
initial Default value
inherit Inherit parent's value

More CSS for Background Image

This following attributes are very useful and almost essential too.

background-size: xpx ypx | x% y%;


background-repeat: no-repeat | repeat | repeat-x | repeat-y;
background-position: left offset (px/%) right offset (px/%) | center center | left top | right
bottom;

Section 5.4: Background Shorthand


The background property can be used to set one or more background related properties:

Value Description CSS Ver.


background-image Background image to use 1+
background-color Background color to apply 1+
background-position Background image's position 1+
background-size Background image's size 3+
background-repeat How to repeat background image 1+
How the background is positioned (ignored when background-attachment is
background-origin 3+
fixed)
How the background is painted relative to the content-box, border-box, or the
background-clip 3+
padding-box
How the background image behaves, whether it scrolls along with its containing
background-attachment 1+
block or has a fixed position within the viewport
initial Sets the property to value to default 3+
inherit Inherits property value from parent 2+

The order of the values does not matter and every value is optional

Syntax

The syntax of the background shorthand declaration is:

background: [<background-image>] [<background-color>] [<background-position>]/[<background-size>]


[<background-repeat>] [<background-origin>] [<background-clip>] [<background-attachment>]
[<initial|inherit>];

GoalKicker.com – CSS Notes for Professionals 26


Examples
background: red;

Simply setting a background-color with the redvalue.

background: border-box red;

Setting a background-clip to border-box and a background-color to red.

background: no-repeat center url("somepng.jpg");

Sets a background-repeat to no-repeat, background-origin to center and a background-image to an image.

background: url('pattern.png') green;

In this example, the background-color of the element would be set to green with pattern.png, if it is available,
overlayed on the colour, repeating as often as necessary to fill the element. If pattern.png includes any
transparency then the green colour will be visible behind it.

background: #000000 url("picture.png") top left / 600px auto no-repeat;

In this example we have a black background with an image 'picture.png' on top, the image does not repeat in either
axis and is positioned in the top left corner. The / after the position is to be able to include the size of the
background image which in this case is set as 600px width and auto for the height. This example could work well
with a feature image that can fade into a solid colour.

NOTE: Use of the shorthand background property resets all previously set background property values,
even if a value is not given. If you wish only to modify a background property value previously set, use a
longhand property instead.

Section 5.5: Background Size


General overview

The background-size property enables one to control the scaling of the background-image. It takes up to two
values, which determine the scale/size of the resulting image in vertical and and horizontal direction. If the property
is missing, its deemed auto in both width and height.

auto will keep the image's aspect ratio, if it can be determined. The height is optional and can be considered auto.
Therefore, on a 256 px × 256 px image, all the following background-size settings would yield an image with height
and width of 50 px:

background-size: 50px;
background-size: 50px auto; /* same as above */
background-size: auto 50px;
background-size: 50px 50px;

So if we started with the following picture (which has the mentioned size of 256 px × 256 px),

GoalKicker.com – CSS Notes for Professionals 27


we'll end up with a 50 px × 50 px on the user's screen, contained in the background of our element:

One can also use percentage values to scale the image with respect of the element. The following example would
yield a 200 px × 133 px drawn image:

#withbackground {
background-image: url(to/some/background.png);

background-size: 100% 66%;

width: 200px;
height: 200px;

padding: 0;
margin: 0;
}

The behaviour depends on the background-origin.

Keeping the aspect ratio

The last example in the previos section lost its original aspect ratio. The circle got into an ellipse, the square into a
rectangle, the triangle into another triangle.

The length or percentage approach isn't flexible enough to keep the aspect ratio at all times. auto doesn't help,
since you might not know which dimension of your element will be larger. However, to cover certain areas with an

GoalKicker.com – CSS Notes for Professionals 28


image (and correct aspect ratio) completely or to contain an image with correct aspect ratio completely in a
background area, the values, contain and cover provide the additional functionality.

Eggsplanation for contain and cover

Sorry for the bad pun, but we're going to use a picture of the day by Biswarup Ganguly for demonstration. Lets say
that this is your screen, and the gray area is outside of your visible screen. For demonstration, We're going to
assume a 16 × 9 ratio.

We want to use the aforementioned picture of the day as a background. However, we cropped the image to 4x3 for
some reason. We could set the background-size property to some fixed length, but we will focus on contain and
cover. Note that I also assume that we didn't mangle the width and/or height of body.

contain

contain

Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its
width and its height can fit inside the background positioning area.

This makes sure that the background image is always completely contained in the background positioning area,
however, there could be some empty space filled with your background-color in this case:

GoalKicker.com – CSS Notes for Professionals 29


cover

cover

Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its
width and its height can completely cover the background positioning area.

This makes sure that the background image is covering everything. There will be no visible background-color,
however depending on the screen's ratio a great part of your image could be cut off:

Demonstration with actual code


div > div {
background-image: url(http://i.stack.imgur.com/r5CAq.jpg);
background-repeat: no-repeat;
background-position: center center;
background-color: #ccc;
border: 1px solid;
width: 20em;
height: 10em;
}
div.contain {
background-size: contain;
}
div.cover {
background-size: cover;
}
/********************************************
Additional styles for the explanation boxes
*********************************************/

div > div {


margin: 0 1ex 1ex 0;
float: left;
}
div + div {
clear: both;
border-top: 1px dashed silver;
padding-top:1ex;
}
div > div::after {
background-color: #000;
color: #fefefe;

GoalKicker.com – CSS Notes for Professionals 30


margin: 1ex;
padding: 1ex;
opacity: 0.8;
display: block;
width: 10ex;
font-size: 0.7em;
content: attr(class);
}

<div>
<div class="contain"></div>
<p>Note the grey background. The image does not cover the whole region, but it's fully
<em>contained</em>.
</p>
</div>
<div>
<div class="cover"></div>
<p>Note the ducks/geese at the bottom of the image. Most of the water is cut, as well as a part
of the sky. You don't see the complete image anymore, but neither do you see any background color;
the image <em>covers</em> all of the <code>&lt;div&gt;</code>.</p>
</div>

Section 5.6: Background Position


The background-position property is used to specify the starting position for a background image or gradient

.myClass {
background-image: url('path/to/image.jpg');
background-position: 50% 50%;
}

The position is set using an X and Y co-ordinate and be set using any of the units used within CSS.

Unit Description

GoalKicker.com – CSS Notes for Professionals 31


A percentage for the horizontal offset is relative to (width of background positioning area - width of
background image).
value% value% A percentage for the vertical offset is relative to (height of background positioning area - height of
background image)
The size of the image is the size given by background-size.
Offsets background image by a length given in pixels relative to the top left of the background
valuepx valuepx
positioning area

Units in CSS can be specified by different methods (see here).

Longhand Background Position Properties

In addition to the shorthand property above, one can also use the longhand background properties background-
position-x and background-position-y. These allow you to control the x or y positions separately.

NOTE: This is supported in all browsers except Firefox (versions 31-48) 2. Firefox 49, to be released
September 2016, will support these properties. Until then, there is a Firefox hack within this Stack
Overflow answer.

Section 5.7: The background-origin property


The background-origin property specifies where the background image is positioned.

Note: If the background-attachment property is set to fixed, this property has no effect.

Default value: padding-box

Possible values:

padding-box - The position is relative to the padding box


border-box - The position is relative to the border box
content-box - The position is relative to the content box
initial
inherit

CSS

.example {
width: 300px;
border: 20px solid black;
padding: 50px;
background: url(https://static.pexels.com/photos/6440/magazines-desk-work-workspace-medium.jpg);
background-repeat: no-repeat;
}

.example1 {}

.example2 { background-origin: border-box; }

.example3 { background-origin: content-box; }

HTML

<p>No background-origin (padding-box is default):</p>

GoalKicker.com – CSS Notes for Professionals 32


<div class="example example1">
<h2>Lorem Ipsum Dolor</h2>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod
tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<p>Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut
aliquip ex ea commodo consequat.</p>
</div>

<p>background-origin: border-box:</p>
<div class="example example2">
<h2>Lorem Ipsum Dolor</h2>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod
tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<p>Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut
aliquip ex ea commodo consequat.</p>
</div>

<p>background-origin: content-box:</p>
<div class="example example3">
<h2>Lorem Ipsum Dolor</h2>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod
tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<p>Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut
aliquip ex ea commodo consequat.</p>
</div>

Result:

GoalKicker.com – CSS Notes for Professionals 33


More:

https://www.w3.org/TR/css3-background/#the-background-origin

https://developer.mozilla.org/en-US/docs/Web/CSS/background-origin

Section 5.8: Multiple Background Image


In CSS3, we can stack multiple background in the same element.

#mydiv {
background-image: url(img_1.png), /* top image */
url(img_2.png), /* middle image */
url(img_3.png); /* bottom image */
background-position: right bottom,
left top,
right top;
background-repeat: no-repeat,
repeat,
no-repeat;
}

Images will be stacked atop one another with the first background on top and the last background in the back.
img_1 will be on top, the img_2 and img_3 is on bottom.

GoalKicker.com – CSS Notes for Professionals 34


We can also use background shorthand property for this:

#mydiv {
background: url(img_1.png) right bottom no-repeat,
url(img_2.png) left top repeat,
url(img_3.png) right top no-repeat;
}

We can also stack images and gradients:

#mydiv {
background: url(image.png) right bottom no-repeat,
linear-gradient(to bottom, #fff 0%,#000 100%);
}

Demo

Section 5.9: Background Attachment


The background-attachment property sets whether a background image is fixed or scrolls with the rest of the page.

body {
background-image: url('img.jpg');
background-attachment: fixed;
}
Value Description
scroll The background scrolls along with the element. This is default.
fixed The background is fixed with regard to the viewport.
local The background scrolls along with the element's contents.
initial Sets this property to its default value.
inherit Inherits this property from its parent element.
Examples
background-attachment: scroll

The default behaviour, when the body is scrolled the background scrolls with it:

body {
background-image: url('image.jpg');
background-attachment: scroll;
}

background-attachment: fixed

The background image will be fixed and will not move when the body is scrolled:

body {
background-image: url('image.jpg');
background-attachment: fixed;
}

background-attachment: local

The background image of the div will scroll when the contents of the div is scrolled.

div {

GoalKicker.com – CSS Notes for Professionals 35


background-image: url('image.jpg');
background-attachment: local;
}

Section 5.10: Background Clip


Definition and Usage: The background-clip property specifies the painting area of the background.

Default value: border-box

Values

border-box is the default value. This allows the background to extend all the way to the outside edge of the
element's border.
padding-box clips the background at the outside edge of the element's padding and does not let it extend
into the border;
content-box clips the background at the edge of the content box.
inherit applies the setting of the parent to the selected element.

CSS

.example {
width: 300px;
border: 20px solid black;
padding: 50px;
background: url(https://static.pexels.com/photos/6440/magazines-desk-work-workspace-medium.jpg);
background-repeat: no-repeat;
}

.example1 {}

.example2 { background-origin: border-box; }

.example3 { background-origin: content-box; }

HTML

<p>No background-origin (padding-box is default):</p>

<div class="example example1">


<h2>Lorem Ipsum Dolor</h2>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod
tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<p>Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut
aliquip ex ea commodo consequat.</p>
</div>

<p>background-origin: border-box:</p>
<div class="example example2">
<h2>Lorem Ipsum Dolor</h2>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod
tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<p>Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut
aliquip ex ea commodo consequat.</p>
</div>

<p>background-origin: content-box:</p>
<div class="example example3">
<h2>Lorem Ipsum Dolor</h2>

GoalKicker.com – CSS Notes for Professionals 36


<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod
tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<p>Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut
aliquip ex ea commodo consequat.</p>
</div>

Section 5.11: Background Repeat


The background-repeat property sets if/how a background image will be repeated.

By default, a background-image is repeated both vertically and horizontally.

div {
background-image: url("img.jpg");
background-repeat: repeat-y;
}

Here's how a background-repeat: repeat-y looks like:

Section 5.12: background-blend-mode Property


.my-div {
width: 300px;
height: 200px;
background-size: 100%;
background-repeat: no-repeat;
background-image: linear-gradient(to right, black 0%,white 100%),
url('https://static.pexels.com/photos/54624/strawberry-fruit-red-sweet-54624-medium.jpeg');
background-blend-mode:saturation;
}

<div class="my-div">Lorem ipsum</div>

GoalKicker.com – CSS Notes for Professionals 37


See result here: https://jsfiddle.net/MadalinaTn/y69d28Lb/

CSS Syntax: background-blend-mode: normal | multiply | screen | overlay | darken | lighten | color-dodge |
saturation | color | luminosity;

Section 5.13: Background Color with Opacity


If you set opacity on an element it will affect all its child elements. To set an opacity just on the background of an
element you will have to use RGBA colors. Following example will have a black background with 0.6 opacity.

/* Fallback for web browsers that don't support RGBa */


background-color: rgb(0, 0, 0);

/* RGBa with 0.6 opacity */


background-color: rgba(0, 0, 0, 0.6);

/* For IE 5.5 - 7*/


filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);

/* For IE 8*/
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000,
endColorstr=#99000000)";

GoalKicker.com – CSS Notes for Professionals 38


Chapter 6: Centering
Section 6.1: Using Flexbox
HTML:

<div class="container">
<img src="http://lorempixel.com/400/200" />
</div>

CSS:

html, body, .container {


height: 100%;
}
.container {
display: flex;
justify-content: center; /* horizontal center */
}
img {
align-self: center; /* vertical center */
}

View Result

HTML:

<img src="http://lorempixel.com/400/200" />

CSS:

html, body {
height: 100%;
}
body {
display: flex;
justify-content: center; /* horizontal center */
align-items: center; /* vertical center */
}

View Result

See Dynamic Vertical and Horizontal Centering under the Flexbox documentation for more details on flexbox and
what the styles mean.

Browser Support

Flexbox is supported by all major browsers, except IE versions before 10.

Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes.

For a quick way to generate prefixes there is Autoprefixer, a third-party tool.

For older browsers (like IE 8 & 9) a Polyfill is available.

For a more detailed look at flexbox browser support, see this answer.

GoalKicker.com – CSS Notes for Professionals 39


Section 6.2: Using CSS transform
CSS transforms are based on the size of the elements so if you don't know how tall or wide your element is, you can
position it absolutely 50% from the top and left of a relative container and translate it by 50% left and upwards to
center it vertically and horizontally.

Keep in mind that with this technique, the element could end being rendered at a non-integer pixel boundary,
making it look blurry. See this answer in SO for a workaround.

HTML

<div class="container">
<div class="element"></div>
</div>

CSS

.container {
position: relative;
}

.element {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

View example in JSFiddle

CROSS BROWSER COMPATIBILITY

The transform property needs prefixes to be supported by older browsers. Prefixes are needed for Chrome<=35,
Safari<=8, Opera<=22, Android Browser<=4.4.4, and IE9. CSS transforms are not supported by IE8 and older
versions.

Here is a common transform declaration for the previous example:

-webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera, Android */


-ms-transform: translate(-50%, -50%); /* IE 9 */
transform: translate(-50%, -50%);

For more information see canIuse.

MORE INFORMATION

The element is being positioned according to the first non-static parent (position: relative, absolute, or
fixed). Explore more in this fiddle and this documentation topic.

For horizontal-only centering, use left: 50% and transform: translateX(-50%). The same goes for vertical-
only centering: center with top: 50% and transform: translateY(-50%).

Using a non-static width/height elements with this method of centering can cause the centered element to
appear squished. This mostly happens with elements containing text, and can be fixed by adding: margin-
right: -50%; and margin-bottom: -50%;. View this fiddle for more information.

GoalKicker.com – CSS Notes for Professionals 40


Section 6.3: Using margin: 0 auto;
Objects can be centered by using margin: 0 auto; if they are block elements and have a defined width.

HTML

<div class="containerDiv">
<div id="centeredDiv"></div>
</div>

<div class="containerDiv">
<p id="centeredParagraph">This is a centered paragraph.</p>
</div>

<div class="containerDiv">
<img id="centeredImage"
src="https://i.kinja-img.com/gawker-media/image/upload/s--c7Q9b4Eh--/c_scale,fl_progressive,q_80,w_
800/qqyvc3bkpyl3mfhr8all.jpg" />
</div>

CSS

.containerDiv {
width: 100%;
height: 100px;
padding-bottom: 40px;
}

#centeredDiv {
margin: 0 auto;
width: 200px;
height: 100px;
border: 1px solid #000;
}

#centeredParagraph {
width: 200px;
margin: 0 auto;
}

#centeredImage {
display: block;
width: 200px;
margin: 0 auto;
}

Result:

GoalKicker.com – CSS Notes for Professionals 41


JSFiddle example: Centering objects with margin: 0 auto;

Section 6.4: Using text-align


The most common and easiest type of centering is that of lines of text in an element. CSS has the rule text-align:
center for this purpose:

HTML

<p>Lorem ipsum</p>

CSS

p {
text-align: center;
}

This does not work for centering entire block elements. text-align controls only alignment of inline content like text in
its parent block element.

See more about text-align in Typography section.

Section 6.5: Using position: absolute


Working in old browsers (IE >= 8)

Automatic margins, paired with values of zero for the left and right or top and bottom offsets, will center an
absolutely positioned elements within its parent.

View Result

HTML

GoalKicker.com – CSS Notes for Professionals 42


<div class="parent">
<img class="center" src="http://lorempixel.com/400/200/" />
</div>

CSS

.parent {
position: relative;
height: 500px;
}

.center {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
}

Elements that don't have their own implicit width and height like images do, will need those values defined.

Other resources: Absolute Centering in CSS

Section 6.6: Using calc()


The calc() function is the part of a new syntax in CSS3 in which you can calculate (mathematically) what size/position
your element occupies by using a variety of values like pixels, percentages, etc. Note: Whenever you use this
function, always take care of the space between two values calc(100% - 80px).

CSS

.center {
position: absolute;
height: 50px;
width: 50px;
background: red;
top: calc(50% - 50px / 2); /* height divided by 2*/
left: calc(50% - 50px / 2); /* width divided by 2*/
}

HTML

<div class="center"></div>

Section 6.7: Using line-height


You can also use line-height to center vertically a single line of text inside a container :

CSS

div {
height: 200px;
line-height: 200px;
}

GoalKicker.com – CSS Notes for Professionals 43


That's quite ugly, but can be useful inside an <input /> element. The line-height property works only when the
text to be centered spans a single line. If the text wraps into multiple lines, the resulting output won't be centered.

Section 6.8: Vertical align anything with 3 lines of code


Supported by IE11+

View Result

Use these 3 lines to vertical align practically everything. Just make sure the div/image you apply the code to has a
parent with a height.

CSS

div.vertical {
position: relative;
top: 50%;
transform: translateY(-50%);
}

HTML

<div class="vertical">Vertical aligned text!</div>

Section 6.9: Centering in relation to another item


We will see how to center content based on the height of a near element.

Compatibility: IE8+, all other modern browsers.

HTML

<div class="content">
<div class="position-container">
<div class="thumb">
<img src="http://lorempixel.com/400/200/">
</div>
<div class="details">
<p class="banner-title">text 1</p>
<p class="banner-text">content content content content content content content content
content content content content content content</p>
<button class="btn">button</button>
</div>
</div>
</div>

CSS

.content * {
box-sizing: border-box;
}
.content .position-container {
display: table;
}
.content .details {
display: table-cell;
vertical-align: middle;

GoalKicker.com – CSS Notes for Professionals 44


width: 33.333333%;
padding: 30px;
font-size: 17px;
text-align: center;
}
.content .thumb {
width: 100%;
}
.content .thumb img {
width: 100%;
}

Link to JSFiddle

The main points are the 3 .thumb, .details and .position-container containers:

The .position-container must have display: table.

The .details must have the real width set width: .... and display: table-cell, vertical-align:
middle.

The .thumb must have width: 100% if you want that it will take all the remaining space and it will be
influenced by the .details width.

The image (if you have an image) inside .thumb should have width: 100%, but it is not necessary if you have
correct proportions.

Section 6.10: Ghost element technique (Michał Czernow's hack)


This technique works even when the container's dimensions are unknown.

Set up a "ghost" element inside the container to be centered that is 100% height, then use vertical-align:
middle on both that and the element to be centered.

CSS

/* This parent can be any width and height */


.block {
text-align: center;

/* May want to do this if there is risk the container may be narrower than the element inside */
white-space: nowrap;
}

/* The ghost element */


.block:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;

/* There is a gap between ghost element and .centered,


caused by space character rendered. Could be eliminated by
nudging .centered (nudge distance depends on font family),
or by zeroing font-size in .parent and resetting it back
(probably to 1rem) in .centered. */
margin-right: -0.25em;
}

GoalKicker.com – CSS Notes for Professionals 45


/* The element to be centered, can also be of any width and height */
.centered {
display: inline-block;
vertical-align: middle;
width: 300px;
white-space: normal; /* Resetting inherited nowrap behavior */
}

HTML

<div class="block">
<div class="centered"></div>
</div>

Section 6.11: Centering vertically and horizontally without


worrying about height or width
The following technique allows you to add your content to an HTML element and center it both horizontally and
vertically without worrying about its height or width.

The outer container

should have display: table;

The inner container

should have display: table-cell;


should have vertical-align: middle;
should have text-align: center;

The content box

should have display: inline-block;


should re-adjust the horizontal text-alignment to eg. text-align: left; or text-align: right;, unless you
want text to be centered

Demo

HTML

<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
You can put anything here!
</div>
</div>
</div>

CSS

body {
margin : 0;
}

.outer-container {
position : absolute;
display: table;
width: 100%; /* This could be ANY width */

GoalKicker.com – CSS Notes for Professionals 46


height: 100%; /* This could be ANY height */
background: #ccc;
}

.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}

.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding: 20px;
border: 1px solid #000;
}

See also this Fiddle!

Section 6.12: Vertically align an image inside div


HTML

<div class="wrap">
<img src="http://lorempixel.com/400/200/" />
</div>

CSS

.wrap {
height: 50px;/* max image height */
width: 100px;
border: 1px solid blue;
text-align: center;
}
.wrap:before {
content:"";
display: inline-block;
height: 100%;
vertical-align: middle;
width: 1px;
}

img {
vertical-align: middle;
}

Section 6.13: Centering with fixed size


If the size of your content is fixed, you can use absolute positioning to 50% with margin that reduces half of your
content's width and height:

HTML

<div class="center">
Center vertically and horizontally
</div>

GoalKicker.com – CSS Notes for Professionals 47


CSS

.center {
position: absolute;
background: #ccc;

left: 50%;
width: 150px;
margin-left: -75px; /* width * -0.5 */

top: 50%;
height: 200px;
margin-top: -100px; /* height * -0.5 */
}

Horizontal centering with only fixed width

You can center the element horizontally even if you don't know the height of the content:

HTML

<div class="center">
Center only horizontally
</div>

CSS

.center {
position: absolute;
background: #ccc;

left: 50%;
width: 150px;
margin-left: -75px; /* width * -0.5 */
}

Vertical centering with fixed height

You can center the element vertically if you know the element's height:

HTML

<div class="center">
Center only vertically
</div>

CSS

.center {
position: absolute;
background: #ccc;

top: 50%;
height: 200px;
margin-top: -100px; /* width * -0.5 */
}

GoalKicker.com – CSS Notes for Professionals 48


Section 6.14: Vertically align dynamic height elements
Applying css intuitively doesn't produce the desired results because

vertical-align:middle isn't applicable to block-level elements


margin-top:auto and margin-bottom:auto used values would compute as zero
margin-top:-50% percentage-based margin values are calculated relative to the width of containing block

For widest browser support, a workaround with helper elements:

HTML

<div class="vcenter--container">
<div class="vcenter--helper">
<div class="vcenter--content">
<!--stuff-->
</div>
</div>
</div>

CSS

.vcenter--container {
display: table;
height: 100%;
position: absolute;
overflow: hidden;
width: 100%;
}
.vcenter--helper {
display: table-cell;
vertical-align: middle;
}
.vcenter--content {
margin: 0 auto;
width: 200px;
}

jsfiddle from original question. This approach

works with dynamic height elements


respects content flow
is supported by legacy browsers

Section 6.15: Horizontal and Vertical centering using table


layout
One could easily center a child element using table display property.

HTML

<div class="wrapper">
<div class="parent">
<div class="child"></div>
</div>
</div>

GoalKicker.com – CSS Notes for Professionals 49


CSS

.wrapper {
display: table;
vertical-align: center;
width: 200px;
height: 200px;
background-color: #9e9e9e;
}
.parent {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
display: inline-block;
vertical-align: middle;
text-align: center;
width: 100px;
height: 100px;
background-color: teal;
}

GoalKicker.com – CSS Notes for Professionals 50


Chapter 7: The Box Model
Parameter Detail
content-box Width and height of the element only includes content area.
padding-box Width and height of the element includes content and padding.
border-box Width and height of the element includes content, padding and border.
initial Sets the box model to its default state.
inherit Inherits the box model of the parent element.

Section 7.1: What is the Box Model?


The Edges

The browser creates a rectangle for each element in the HTML document. The Box Model describes how the
padding, border, and margin are added to the content to create this rectangle.

Diagram from CSS2.2 Working Draft

The perimeter of each of the four areas is called an edge. Each edge defines a box.

The innermost rectangle is the content box. The width and height of this depends on the element's
rendered content (text, images and any child elements it may have).
Next is the padding box, as defined by the padding property. If there is no padding width defined, the
padding edge is equal to the content edge.
Then we have the border box, as defined by the border property. If there is no border width defined, the
border edge is equal to the padding edge.
The outermost rectangle is the margin box, as defined by the margin property. If there is no margin width
defined, the margin edge is equal to the border edge.

Example
div {
border: 5px solid red;
margin: 50px;
padding: 20px;

GoalKicker.com – CSS Notes for Professionals 51


}

This CSS styles all div elements to have a top, right, bottom and left border of 5px in width; a top, right, bottom and
left margin of 50px; and a top, right, bottom, and left padding of 20px. Ignoring content, our generated box will look
like this:

Screenshot of Google Chrome's Element Styles panel

As there is no content, the content region (the blue box in the middle) has no height or width (0px by 0px).
The padding box by default is the same size as the content box, plus the 20px width on all four edges we're
defining above with the padding property (40px by 40px).
The border box is the same size as the padding box, plus the 5px width we're defining above with the border
property (50px by 50px).
Finally the margin box is the same size as the border box, plus the 50px width we're defining above with the
margin property (giving our element a total size of 150px by 150px).

Now lets give our element a sibling with the same style. The browser looks at the Box Model of both elements to
work out where in relation to the previous element's content the new element should be positioned:

The content of each of element is separated by a 150px gap, but the two elements' boxes touch each other.

If we then modify our first element to have no right margin, the right margin edge would be in the same position as
the right border edge, and our two elements would now look like this:

Section 7.2: box-sizing


The default box model (content-box) can be counter-intuitive, since the width / height for an element will not
represent its actual width or height on screen as soon as you start adding padding and border styles to the

GoalKicker.com – CSS Notes for Professionals 52


element.

The following example demonstrates this potential issue with content-box:

textarea {
width: 100%;
padding: 3px;
box-sizing: content-box; /* default value */
}

Since the padding will be added to the width of the textarea, the resulting element is a textarea that is wider than
100%.

Fortunately, CSS allows us to change the box model with the box-sizing property for an element. There are three
different values for the property available:

content-box: The common box model - width and height only includes the content, not the padding or
border

padding-box: Width and height includes the content and the padding, but not the border

border-box: Width and height includes the content, the padding as well as the border

To solve the textarea problem above, you could just change the box-sizing property to padding-box or border-
box. border-box is most commonly used.

textarea {
width: 100%;
padding: 3px;
box-sizing: border-box;
}

To apply a specific box model to every element on the page, use the following snippet:

html {
box-sizing: border-box;
}

*, *:before, *:after {

GoalKicker.com – CSS Notes for Professionals 53


box-sizing: inherit;
}

In this coding box-sizing:border-box; is not directly applied to *, so you can easily overwrite this property on
individual elements.

GoalKicker.com – CSS Notes for Professionals 54


Chapter 8: Margins
Parameter Details
0 set margin to none
auto used for centering, by evenly setting values on each side
units (e.g. px) see parameter section in Units for a list of valid units
inherit inherit margin value from parent element
initial restore to initial value

Section 8.1: Margin Collapsing


When two margins are touching each other vertically, they are collapsed. When two margins touch horizontally,
they do not collapse.

Example of adjacent vertical margins:

Consider the following styles and markup:

div{
margin: 10px;
}

<div>
some content
</div>
<div>
some more content
</div>

They will be 10px apart since vertical margins collapse over one and other. (The spacing will not be the sum of two
margins.)

Example of adjacent horizontal margins:

Consider the following styles and markup:

span{
margin: 10px;
}

<span>some</span><span>content</span>

They will be 20px apart since horizontal margins don't collapse over one and other. (The spacing will be the sum of
two margins.)

Overlapping with different sizes

.top{
margin: 10px;
}
.bottom{
margin: 15px;
}

<div class="top">
some content

GoalKicker.com – CSS Notes for Professionals 55


</div>
<div class="bottom">
some more content
</div>

These elements will be spaced 15px apart vertically. The margins overlap as much as they can, but the larger
margin will determine the spacing between the elements.

Overlapping margin gotcha

.outer-top{
margin: 10px;
}
.inner-top{
margin: 15px;
}
.outer-bottom{
margin: 20px;
}
.inner-bottom{
margin: 25px;
}

<div class="outer-top">
<div class="inner-top">
some content
</div>
</div>
<div class="outer-bottom">
<div class="inner-bottom">
some more content
</div>
</div>

What will be the spacing between the two texts? (hover to see answer)

The spacing will be 25px. Since all four margins are touching each other, they will collapse, thus using the
largest margin of the four.

Now, what about if we add some borders to the markup above.

div{
border: 1px solid red;
}

What will be the spacing between the two texts? (hover to see answer)

The spacing will be 59px! Now only the margins of .outer-top and .outer-bottom touch each other, and
are the only collapsed margins. The remaining margins are separated by the borders. So we have 1px +
10px + 1px + 15px + 20px + 1px + 25px + 1px. (The 1px's are the borders...)

Collapsing Margins Between Parent and Child Elements:

HTML:

GoalKicker.com – CSS Notes for Professionals 56


<h1>Title</h1>
<div>
<p>Paragraph</p>
</div>

CSS

h1 {
margin: 0;
background: #cff;
}
div {
margin: 50px 0 0 0;
background: #cfc;
}
p {
margin: 25px 0 0 0;
background: #cf9;
}

In the example above, only the largest margin applies. You may have expected that the paragraph would be located
60px from the h1 (since the div element has a margin-top of 40px and the p has a 20px margin-top). This does not
happen because the margins collapse together to form one margin.

Section 8.2: Apply Margin on a Given Side


Direction-Specific Properties

CSS allows you to specify a given side to apply margin to. The four properties provided for this purpose are:

margin-left
margin-right
margin-top
margin-bottom

The following code would apply a margin of 30 pixels to the left side of the selected div. View Result

HTML

<div id="myDiv"></div>

CSS

#myDiv {
margin-left: 30px;
height: 40px;
width: 40px;
background-color: red;
}
Parameter Details
margin-left The direction in which the margin should be applied.
30px The width of the margin.
Specifying Direction Using Shorthand Property

The standard margin property can be expanded to specify differing widths to each side of the selected elements.
The syntax for doing this is as follows:

GoalKicker.com – CSS Notes for Professionals 57


margin: <top> <right> <bottom> <left>;

The following example applies a zero-width margin to the top of the div, a 10px margin to the right side, a 50px
margin to the left side, and a 100px margin to the left side. View Result

HTML

<div id="myDiv"></div>

CSS

#myDiv {
margin: 0 10px 50px 100px;
height: 40px;
width: 40px;
background-color: red;
}

Section 8.3: Margin property simplification


p {
margin:1px; /* 1px margin in all directions */

/*equals to:*/

margin:1px 1px;

/*equals to:*/

margin:1px 1px 1px;

/*equals to:*/

margin:1px 1px 1px 1px;


}

Another exapmle:

p{
margin:10px 15px; /* 10px margin-top & bottom And 15px margin-right & left*/

/*equals to:*/

margin:10px 15px 10px 15px;

/*equals to:*/

margin:10px 15px 10px;


/* margin left will be calculated from the margin right value (=15px) */
}

Section 8.4: Horizontally center elements on a page using


margin
As long as the element is a block, and it has an explicitly set width value, margins can be used to center block
elements on a page horizontally.

GoalKicker.com – CSS Notes for Professionals 58


We add a width value that is lower than the width of the window and the auto property of margin then distributes
the remaining space to the left and the right:

#myDiv {
width:80%;
margin:0 auto;
}

In the example above we use the shorthand margin declaration to first set 0 to the top and bottom margin values
(although this could be any value) and then we use auto to let the browser allocate the space automatically to the
left and right margin values.

In the example above, the #myDiv element is set to 80% width which leaves use 20% leftover. The browser
distributes this value to the remaining sides so:

(100% - 80%) / 2 = 10%

Section 8.5: Example 1:


It is obvious to assume that the percentage value of margin to margin-left and margin-right would be relative to
its parent element.

.parent {
width : 500px;
height: 300px;
}

.child {
width : 100px;
height: 100px;
margin-left: 10%; /* (parentWidth * 10/100) => 50px */
}

But that is not the case, when comes to margin-top and margin-bottom. Both these properties, in percentages,
aren't relative to the height of the parent container but to the width of the parent container.

So,

.parent {
width : 500px;
height: 300px;
}

.child {
width : 100px;
height: 100px;
margin-left: 10%; /* (parentWidth * 10/100) => 50px */
margin-top: 20%; /* (parentWidth * 20/100) => 100px */
}

Section 8.6: Negative margins


Margin is one of a few CSS properties that can be set to negative values. This property can be used to overlap
elements without absolute positioning.

div{

GoalKicker.com – CSS Notes for Professionals 59


display: inline;
}

#over{
margin-left: -20px;
}

<div>Base div</div>
<div id="over">Overlapping div</div>

GoalKicker.com – CSS Notes for Professionals 60


Chapter 9: Padding
Section 9.1: Padding Shorthand
The padding property sets the padding space on all sides of an element. The padding area is the space between the
content of the element and its border. Negative values are not allowed.

To save adding padding to each side individually (using padding-top, padding-left etc) can you write it as a
shorthand, as below:

Four values:

<style>
.myDiv {
padding: 25px 50px 75px 100px; /* top right bottom left; */
}
</style>
<div class="myDiv"></div>

Three values:

<style>
.myDiv {
padding: 25px 50px 75px; /* top left/right bottom */
}
</style>
<div class="myDiv"></div>

Two values:

<style>
.myDiv {
padding: 25px 50px; /* top/bottom left/right */
}
</style>
<div class="myDiv"></div>

One value:

<style>
.myDiv {

GoalKicker.com – CSS Notes for Professionals 61


padding: 25px; /* top/right/bottom/left */
}
</style>
<div class="myDiv"></div>

Section 9.2: Padding on a given side


The padding property sets the padding space on all sides of an element. The padding area is the space between the
content of the element and its border. Negative values are not allowed.

You can specify a side individually:

padding-top
padding-right
padding-bottom
padding-left

The following code would add a padding of 5px to the top of the div:

<style>
.myClass {
padding-top: 5px;
}
</style>

<div class="myClass"></div>

GoalKicker.com – CSS Notes for Professionals 62


Chapter 10: Border
Section 10.1: border-radius
The border-radius property allows you to change the shape of the basic box model.

Every corner of an element can have up to two values, for the vertical and horizontal radius of that corner (for a
maximum of 8 values).

The first set of values defines the horizontal radius. The optional second set of values, preceded by a ‘/’ , defines the
vertical radius. If only one set of values is supplied, it is used for both the vertical and horizontal radius.

border-radius: 10px 5% / 20px 25em 30px 35em;

The 10px is the horizontal radius of the top-left-and-bottom-right. And the 5% is the horizontal radius of the top-
right-and-bottom-left. The other four values after '/' are the vertical radii for top-left, top-right, bottom-right and
bottom-left.

As with many CSS properties, shorthands can be used for any or all possible values. You can therefore specify
anything from one to eight values. The following shorthand allows you to set the horizontal and vertical radius of
every corner to the same value:

HTML:

<div class='box'></div>

CSS:

.box {
width: 250px;
height: 250px;
background-color: black;
border-radius: 10px;
}

Border-radius is most commonly used to convert box elements into circles. By setting the border-radius to half of
the length of a square element, a circular element is created:

.circle {
width: 200px;
height: 200px;
border-radius: 100px;
}

GoalKicker.com – CSS Notes for Professionals 63


Because border-radius accepts percentages, it is common to use 50% to avoid manually calculating the border-
radius value:

.circle {
width: 150px;
height: 150px;
border-radius: 50%;
}

If the width and height properties are not equal, the resulting shape will be an oval rather than a circle.

Browser specific border-radius example:

-webkit-border-top-right-radius: 4px;
-webkit-border-bottom-right-radius: 4px;
-webkit-border-bottom-left-radius: 0;
-webkit-border-top-left-radius: 0;
-moz-border-radius-topright: 4px;
-moz-border-radius-bottomright: 4px;
-moz-border-radius-bottomleft: 0;
-moz-border-radius-topleft: 0;
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
border-bottom-left-radius: 0;
border-top-left-radius: 0;

Section 10.2: border-style


The border-style property sets the style of an element's border. This property can have from one to four values
(for every side of the element one value.)

Examples:

border-style: dotted;

border-style: dotted solid double dashed;

border-style can also have the values none and hidden. They have the same effect, except hidden works for
border conflict resolution for <table> elements. In a <table> with multiple borders, none has the lowest priority
(meaning in a conflict, the border would show), and hidden has the highest priority (meaning in a conflict, the
border would not show).

GoalKicker.com – CSS Notes for Professionals 64


Section 10.3: Multiple Borders
Using outline:

.div1{
border: 3px solid black;
outline: 6px solid blue;
width: 100px;
height: 100px;
margin: 20px;
}

Using box-shadow:

.div2{
border: 5px solid green;
box-shadow: 0px 0px 0px 4px #000;
width: 100px;
height: 100px;
margin: 20px;
}

Using a pseudo element:

.div3 {
position: relative;
border: 5px solid #000;
width: 100px;
height: 100px;
margin: 20px;
}
.div3:before {
content: " ";
position: absolute;
border: 5px solid blue;
z-index: -1;
top: 5px;
left: 5px;
right: 5px;
bottom: 5px;
}

GoalKicker.com – CSS Notes for Professionals 65


http://jsfiddle.net/MadalinaTn/bvqpcohm/2/

Section 10.4: border (shorthands)


In most cases you want to define several border properties (border-width, border-style and border-color) for all
sides of an element.

Instead of writing:

border-width: 1px;
border-style: solid;
border-color: #000;

You can simply write:

border: 1px solid #000;

These shorthands are also available for every side of an element: border-top, border-left, border-right and
border-bottom. So you can do:

border-top: 2px double #aaaaaa;

Section 10.5: border-collapse


The border-collapse property applies only to tables (and elements displayed as display: table or inline-
table) and sets whether the table borders are collapsed into a single border or detached as in standard HTML.

table {
border-collapse: separate; /* default */
border-spacing: 2px; /* Only works if border-collapse is separate */
}

Also see Tables - border-collapse documentation entry

GoalKicker.com – CSS Notes for Professionals 66


Section 10.6: border-image
With the border-image property you have the possibility to set an image to be used instead of normal border
styles.

A border-image essentially consist of a

border-image-source: The path to the image to be used


border-image-slice: Specifies the offset that is used to divide the image into nine regions (four corners,
four edges and a middle)
border-image-repeat: Specifies how the images for the sides and the middle of the border image are scaled

Consider the following example wheras border.png is a image of 90x90 pixels:

border-image: url("border.png") 30 stretch;

The image will be split into nine regions with 30x30 pixels. The edges will be used as the corners of the border while
the side will be used in between. If the element is higher / wider than 30px this part of the image will be stretched.
The middle part of the image defaults to be transparent.

Section 10.7: Creating a multi-colored border using border-


image
CSS
.bordered {
border-image: linear-gradient(to right, red 20%, green 20%, green 40%, blue 40%, blue 60%, maroon
60%, maroon 80%, chocolate 80%); /* gradient with required colors */
border-image-slice: 1;
}

HTML
<div class='bordered'>Border on all sides</div>

The above example would produce a border that comprises of 5 different colors. The colors are defined through a
linear-gradient (you can find more information about gradients in the docs). You can find more information
about border-image-slice property in the border-image example in same page.

(Note: Additional properties were added to the element for presentational purpose.)

You'd have noticed that the left border has only a single color (the start color of the gradient) while the right border
also has only a single color (the gradient's end color). This is because of the way that border image property works.
It is as though the gradient is applied to the entire box and then the colors are masked from the padding and
content areas, thus making it look as though only the border has the gradient.

Which border(s) have a single color is dependant on the gradient definition. If the gradient is a to right gradient,
the left border would be the start color of the gradient and right border would be the end color. If it was a to
bottom gradient the top border would be the gradient's start color and bottom border would be end color. Below is

GoalKicker.com – CSS Notes for Professionals 67


the output of a to bottom 5 colored gradient.

If the border is required only on specific sides of the element then the border-width property can be used just like
with any other normal border. For example, adding the below code would produce a border only on the top of the
element.

border-width: 5px 0px 0px 0px;

Note that, any element that has border-image property won't respect the border-radius (that is the border won't
curve). This is based on the below statement in the spec:

A box's backgrounds, but not its border-image, are clipped to the appropriate curve (as determined by
‘background-clip’).

Section 10.8: border-[left|right|top|bottom]


The border-[left|right|top|bottom] property is used to add a border to a specific side of an element.

For example if you wanted to add a border to the left side of an element, you could do:

#element {
border-left: 1px solid black;
}

GoalKicker.com – CSS Notes for Professionals 68


Chapter 11: Outlines
Parameter Details
dotted dotted outline
dashed dashed outline
solid solid outline
double double outline
groove 3D grooved outline, depends on the outline-color value
ridge 3D ridged outline, depends on the outline-color value
inset 3D inset outline, depends on the outline-color value
outset 3D outset outline, depends on the outline-color value
none no outline
hidden hidden outline

Section 11.1: Overview


Outline is a line that goes around the element, outside of the border. In contrast to border, outlines do not take any
space in the box model. So adding an outline to an element does not affect the position of the element or other
elements.

In addition, outlines can be non-rectangular in some browsers. This can happen if outline is applied on a span
element that has text with different font-size properties inside it. Unlike borders, outlines cannot have rounded
corners.

The essential parts of outline are outline-color, outline-style and outline-width.

The definition of an outline is equivalent to the definition of a border:

An outline is a line around an element. It is displayed around the margin of the element. However, it is
different from the border property.

outline: 1px solid black;

Section 11.2: outline-style


The outline-style property is used to set the style of the outline of an element.

p {
border: 1px solid black;
outline-color:blue;
line-height:30px;
}
.p1{
outline-style: dotted;
}
.p2{
outline-style: dashed;
}
.p3{
outline-style: solid;
}

GoalKicker.com – CSS Notes for Professionals 69


.p4{
outline-style: double;
}
.p5{
outline-style: groove;
}
.p6{
outline-style: ridge;
}
.p7{
outline-style: inset;
}
.p8{
outline-style: outset;
}

HTML

<p class="p1">A dotted outline</p>


<p class="p2">A dashed outline</p>
<p class="p3">A solid outline</p>
<p class="p4">A double outline</p>
<p class="p5">A groove outline</p>
<p class="p6">A ridge outline</p>
<p class="p7">An inset outline</p>
<p class="p8">An outset outline</p>

GoalKicker.com – CSS Notes for Professionals 70


Chapter 12: Overflow
Overflow Value Details
visible Shows all overflowing content outside the element
scroll Hides the overflowing content and adds a scroll bar
hidden Hides the overflowing content, both scroll bars disappear and the page becomes fixed
auto Same as scroll if content overflows, but doesn't add scroll bar if content fits
inherit Inherit's the parent element's value for this property

Section 12.1: overflow-wrap


overflow-wrap tells a browser that it can break a line of text inside a targeted element onto multiple lines in an
otherwise unbreakable place. Helpful in preventing an long string of text causing layout problems due to
overflowing it's container.

CSS

div {
width:100px;
outline: 1px dashed #bbb;
}

#div1 {
overflow-wrap:normal;
}

#div2 {
overflow-wrap:break-word;
}

HTML

<div id="div1">
<strong>#div1</strong>: Small words are displayed normally, but a long word like <span
style="red;">supercalifragilisticexpialidocious</span> is too long so it will overflow past the
edge of the line-break
</div>

<div id="div2">
<strong>#div2</strong>: Small words are displayed normally, but a long word like <span
style="red;">supercalifragilisticexpialidocious</span> will be split at the line break and continue
on the next line.
</div>

GoalKicker.com – CSS Notes for Professionals 71


overflow-wrap – Value Details
normal Lets a word overflow if it is longer than the line
break-word Will split a word into multiple lines, if necessary
inherit Inherits the parent element's value for this property

Section 12.2: overflow-x and overflow-y


These two properties work in a similar fashion as the overflow property and accept the same values. The
overflow-x parameter works only on the x or left-to-right axis. The overflow-y works on the y or top-to-bottom
axis.

HTML

<div id="div-x">
If this div is too small to display its contents,
the content to the left and right will be clipped.
</div>

<div id="div-y">
If this div is too small to display its contents,
the content to the top and bottom will be clipped.
</div>

CSS

div {
width: 200px;
height: 200px;
}

#div-x {
overflow-x: hidden;
}

GoalKicker.com – CSS Notes for Professionals 72


#div-y {
overflow-y: hidden;
}

Section 12.3: overflow: scroll


HTML

<div>
This div is too small to display its contents to display the effects of the overflow property.
</div>

CSS

div {
width:100px;
height:100px;
overflow:scroll;
}

Result

The content above is clipped in a 100px by 100px box, with scrolling available to view overflowing content.

Most desktop browsers will display both horizontal and vertical scrollbars, whether or not any content is clipped.
This can avoid problems with scrollbars appearing and disappearing in a dynamic environment. Printers may print
overflowing content.

Section 12.4: overflow: visible


HTML

<div>
Even if this div is too small to display its contents, the content is not clipped.
</div>

CSS

div {
width:50px;
height:50px;
overflow:visible;
}

Result

GoalKicker.com – CSS Notes for Professionals 73


Content is not clipped and will be rendered outside the content box if it exceeds its container size.

Section 12.5: Block Formatting Context Created with Overflow


Using the overflow property with a value different to visible will create a new block formatting context. This is
useful for aligning a block element next to a floated element.

CSS

img {
float:left;
margin-right: 10px;
}
div {
overflow:hidden; /* creates block formatting context */
}

HTML

<img src="http://placehold.it/100x100">
<div>
<p>Lorem ipsum dolor sit amet, cum no paulo mollis pertinacia.</p>
<p>Ad case omnis nam, mutat deseruisse persequeris eos ad, in tollit debitis sea.</p>
</div>

Result

GoalKicker.com – CSS Notes for Professionals 74


This example shows how paragraphs within a div with the overflow property set will interact with a floated image.

GoalKicker.com – CSS Notes for Professionals 75


Chapter 13: Media Queries
Parameter Details
mediatype (Optional) This is the type of media. Could be anything in the range of all to screen.
(Optional) Doesn't apply the CSS for this particular media type and applies for everything
not
else.
media feature Logic to identify use case for CSS. Options outlined below.
Media Feature Details
aspect-ratio Describes the aspect ratio of the targeted display area of the output device.
Indicates the number of bits per color component of the output device. If the device is not a
color
color device, this value is zero.
color-index Indicates the number of entries in the color look-up table for the output device.
grid Determines whether the output device is a grid device or a bitmap device.
height The height media feature describes the height of the output device's rendering surface.
max-width CSS will not apply on a screen width wider than specified.
min-width CSS will not apply on a screen width narrower than specified.
max-height CSS will not apply on a screen height taller than specified.
min-height CSS will not apply on a screen height shorter than specified.
monochrome Indicates the number of bits per pixel on a monochrome (greyscale) device.
orientation CSS will only display if device is using specified orientation. See remarks for more details.
resolution Indicates the resolution (pixel density) of the output device.
scan Describes the scanning process of television output devices.
The width media feature describes the width of the rendering surface of the output device
width
(such as the width of the document window, or the width of the page box on a printer).
Deprecated Features Details
Deprecated CSS will only display on devices whose height/width ratio matches the specified
device-aspect-ratio
ratio. This is adeprecatedfeature and is not guaranteed to work.
Deprecated Same as max-width but measures the physical screen width, rather than the
max-device-width
display width of the browser.
Deprecated Same as min-width but measures the physical screen width, rather than the
min-device-width
display width of the browser.
Deprecated Same as max-height but measures the physical screen width, rather than the
max-device-height
display width of the browser.
Deprecated Same as min-height but measures the physical screen width, rather than the
min-device-height
display width of the browser.

Section 13.1: Terminology and Structure


Media queries allow one to apply CSS rules based on the type of device / media (e.g. screen, print or handheld)
called media type, additional aspects of the device are described with media features such as the availability of
color or viewport dimensions.

General Structure of a Media Query


@media [...] {
/* One or more CSS rules to apply when the query is satisfied */
}

A Media Query containing a Media Type


@media print {
/* One or more CSS rules to apply when the query is satisfied */

GoalKicker.com – CSS Notes for Professionals 76


}

A Media Query containing a Media Type and a Media Feature


@media screen and (max-width: 600px) {
/* One or more CSS rules to apply when the query is satisfied */
}

A Media Query containing a Media Feature (and an implicit Media Type of "all")
@media (orientation: portrait) {
/* One or more CSS rules to apply when the query is satisfied */
}

Section 13.2: Basic Example


@media screen and (min-width: 720px) {
body {
background-color: skyblue;
}
}

The above media query specifies two conditions:

1. The page must be viewed on a normal screen (not a printed page, projector, etc).
2. The width of the user's view port must be at least 720 pixels.

If these conditions are met, the styles inside the media query will be active, and the background color of the page
will be sky blue.

Media queries are applied dynamically. If on page load the conditions specified in the media query are met, the CSS
will be applied, but will be immediately disabled should the conditions cease to be met. Conversely, if the
conditions are initially not met, the CSS will not be applied until the specified conditions are met.

In our example, if the user's view port width is initially greater than 720 pixels, but the user shrinks the browser's
width, the background color will cease to be sky blue as soon as the user has resized the view port to less than 720
pixels in width.

Section 13.3: mediatype


Media queries have an optional mediatype parameter. This parameter is placed directly after the @media
declaration (@media mediatype), for example:

@media print {
html {
background-color: white;
}
}

The above CSS code will give the DOM HTML element a white background color when being printed.

The mediatype parameter has an optional not or only prefix that will apply the styles to everything except the
specified mediatype or only the specified media type, respectively. For example, the following code example will
apply the style to every media type except print.

@media not print {


html {
background-color: green;
}

GoalKicker.com – CSS Notes for Professionals 77


}

And the same way, for just showing it only on the screen, this can be used:

@media only screen {


.fadeInEffects {
display: block;
}
}

The list of mediatype can be understood better with the following table:

Media Type Description


all Apply to all devices
screen Default computers
print Printers in general. Used to style print-versions of websites
handheld PDA's, cellphones and hand-held devices with a small screen
projection For projected presentation, for example projectors
aural Speech Systems
braille Braille tactile devices
embossed Paged braille printers
tv Television-type devices
tty Devices with a fixed-pitch character grid. Terminals, portables.

Section 13.4: Media Queries for Retina and Non Retina


Screens
Although this works only for WebKit based browsers, this is helpful:

/* ----------- Non-Retina Screens ----------- */


@media screen
and (min-width: 1200px)
and (max-width: 1600px)
and (-webkit-min-device-pixel-ratio: 1) {
}

/* ----------- Retina Screens ----------- */


@media screen
and (min-width: 1200px)
and (max-width: 1600px)
and (-webkit-min-device-pixel-ratio: 2)
and (min-resolution: 192dpi) {
}

Background Information

There are two types of pixels in the display. One is the logical pixels and the other is the physical pixels. Mostly, the
physical pixels always stay the same, because it is the same for all the display devices. The logical pixels change
based on the resolution of the devices to display higher quality pixels. The device pixel ratio is the ratio between
physical pixels and logical pixels. For instance, the MacBook Pro Retina, iPhone 4 and above report a device pixel
ratio of 2, because the physical linear resolution is double the logical resolution.

The reason why this works only with WebKit based browsers is because of:

GoalKicker.com – CSS Notes for Professionals 78


The vendor prefix -webkit- before the rule.
This hasn't been implemented in engines other than WebKit and Blink.

Section 13.5: Width vs Viewport


When we are using "width" with media queries it is important to set the meta tag correctly. Basic meta tag looks like
this and it needs to be put inside the <head> tag.

<meta name="viewport" content="width=device-width,initial-scale=1">

Why this is important?

Based on MDN's definition "width" is

The width media feature describes the width of the rendering surface of the output device (such as the
width of the document window, or the width of the page box on a printer).

What does that mean?

View-port is the width of the device itself. If your screen resolution says the resolution is 1280 x 720, your view-port
width is "1280px".

More often many devices allocate different pixel amount to display one pixel. For an example iPhone 6 Plus has
1242 x 2208 resolution. But the actual viewport-width and viewport-height is 414 x 736. That means 3 pixels are
used to create 1 pixel.

But if you did not set the meta tag correctly it will try to show your webpage with its native resolution which results
in a zoomed out view (smaller texts and images).

Section 13.6: Using Media Queries to Target Dierent Screen


Sizes
Often times, responsive web design involves media queries, which are CSS blocks that are only executed if a
condition is satisfied. This is useful for responsive web design because you can use media queries to specify
different CSS styles for the mobile version of your website versus the desktop version.

@media only screen and (min-width: 300px) and (max-width: 767px) {


.site-title {
font-size: 80%;
}

/* Styles in this block are only applied if the screen size is atleast 300px wide, but no more
than 767px */
}

@media only screen and (min-width: 768px) and (max-width: 1023px) {


.site-title {
font-size: 90%;
}

/* Styles in this block are only applied if the screen size is atleast 768px wide, but no more
than 1023px */
}

@media only screen and (min-width: 1024px) {

GoalKicker.com – CSS Notes for Professionals 79


.site-title {
font-size: 120%;
}

/* Styles in this block are only applied if the screen size is over 1024px wide. */
}

Section 13.7: Use on link tag


<link rel="stylesheet" media="min-width: 600px" href="example.css" />

This stylesheet is still downloaded but is applied only on devices with screen width larger than 600px.

Section 13.8: Media queries and IE8


Media queries are not supported at all in IE8 and below.

A Javascript based workaround

To add support for IE8, you could use one of several JS solutions. For example, Respond can be added to add
media query support for IE8 only with the following code :

<!--[if lt IE 9]>
<script
src="respond.min.js">
</script>
<![endif]-->

CSS Mediaqueries is another library that does the same thing. The code for adding that library to your HTML would
be identical :

<!--[if lt IE 9]>
<script
src="css3-mediaqueries.js">
</script>
<![endif]-->

The alternative

If you don't like a JS based solution, you should also consider adding an IE<9 only stylesheet where you adjust your
styling specific to IE<9. For that, you should add the following HTML to your code:

<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" media="all" href="style-ielt9.css"/>
<![endif]-->

Note :

Technically it's one more alternative: using CSS hacks to target IE<9. It has the same impact as an IE<9 only
stylesheet, but you don't need a separate stylesheet for that. I do not recommend this option, though, as they
produce invalid CSS code (which is but one of several reasons why the use of CSS hacks is generally frowned upon
today).

GoalKicker.com – CSS Notes for Professionals 80


Chapter 14: Floats
Section 14.1: Float an Image Within Text
The most basic use of a float is having text wrap around an image. The below code will produce two paragraphs
and an image, with the second paragraph flowing around the image. Notice that it is always content after the
floated element that flows around the floated element.

HTML:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed
cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis
ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia
arcu eget nulla. </p>

<img src="http://lorempixel.com/200/100/" />

<p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.
Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque
nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin
ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non,
massa. Fusce ac turpis quis ligula lacinia aliquet. </p>

CSS:

img {
float:left;
margin-right:1rem;
}

This will be the output

GoalKicker.com – CSS Notes for Professionals 81


Codepen Link

Section 14.2: clear property


The clear property is directly related to floats. Property Values:

none - Default. Allows floating elements on both sides


left - No floating elements allowed on the left side
right - No floating elements allowed on the right side
both - No floating elements allowed on either the left or the right side
initial - Sets this property to its default value. Read about initial
inherit - Inherits this property from its parent element. Read about inherit

<html>
<head>
<style>
img {
float: left;

GoalKicker.com – CSS Notes for Professionals 82


}

p.clear {
clear: both;
}
</style>
</head>
<body>

<img src="https://static.pexels.com/photos/69372/pexels-photo-69372-medium.jpeg" width="100">


<p>Lorem ipsoum Lorem ipsoum Lorem ipsoum Lorem ipsoum Lorem ipsoum Lorem ipsoum Lorem ipsoum Lorem
ipsoum Lorem ipsoum Lorem ipsoum Lorem ipsoum Lorem ipsoum </p>
<p class="clear">Lorem ipsoum Lorem ipsoum Lorem ipsoum Lorem ipsoum Lorem ipsoum Lorem ipsoum
Lorem ipsoum Lorem ipsoum Lorem ipsoum Lorem ipsoum Lorem ipsoum Lorem ipsoum </p>

</body>
</html>

Section 14.3: Clearfix

The clearfix hack is a popular way to contain floats (N. Gallagher aka @necolas)

Not to be confused with the clear property, clearfix is a concept (that is also related to floats, thus the possible
confusion). To contain floats, you've to add .cf or .clearfix class on the container (the parent) and style this class
with a few rules described below.

3 versions with slightly different effects (sources :A new micro clearfix hack by N. Gallagher and clearfix reloaded by
T. J. Koblentz):

Clearfix (with top margin collapsing of contained floats still occurring)


.cf:after {
content: "";
display: table;
}

.cf:after {
clear: both;
}

Clearfix also preventing top margin collapsing of contained floats


/**
* For modern browsers
* 1. The space content is one way to avoid an Opera bug when the
* contenteditable attribute is included anywhere else in the document.
* Otherwise it causes space to appear at the top and bottom of elements
* that are clearfixed.
* 2. The use of `table` rather than `block` is only necessary if using
* `:before` to contain the top-margins of child elements.
*/
.cf:before,
.cf:after {
content: " "; /* 1 */
display: table; /* 2 */
}

.cf:after {
clear: both;

GoalKicker.com – CSS Notes for Professionals 83


}

Clearfix with support of outdated browsers IE6 and IE7


.cf:before,
.cf:after {
content: " ";
display: table;
}

.cf:after {
clear: both;
}

/**
* For IE 6/7 only
* Include this rule to trigger hasLayout and contain floats.
*/
.cf {
*zoom: 1;
}

Codepen showing clearfix effect

Other resource: Everything you know about clearfix is wrong (clearfix and BFC - Block Formatting Context while
hasLayout relates to outdated browsers IE6 maybe 7)

Section 14.4: In-line DIV using float


The div is a block-level element, i.e it occupies the whole of the page width and the siblings are place one below the
other irrespective of their width.

<div>
<p>This is DIV 1</p>
</div>
<div>
<p>This is DIV 2</p>
</div>

The output of the following code will be

GoalKicker.com – CSS Notes for Professionals 84


We can make them in-line by adding a float css property to the div.

HTML:

<div class="outer-div">
<div class="inner-div1">
<p>This is DIV 1</p>
</div>
<div class="inner-div2">
<p>This is DIV 2</p>
</div>
</div>

CSS

.inner-div1 {
width: 50%;
margin-right:0px;
float:left;
background : #337ab7;
padding:50px 0px;
}

.inner-div2 {
width: 50%;
margin-right:0px;
float:left;
background : #dd2c00;
padding:50px 0px;
}

p {
text-align:center;
}

GoalKicker.com – CSS Notes for Professionals 85


Codepen Link

Section 14.5: Use of overflow property to clear floats


Setting overflow value to hidden,auto or scroll to an element, will clear all the floats within that element.

Note: using overflow:scroll will always show the scrollbox

Section 14.6: Simple Two Fixed-Width Column Layout


A simple two-column layout consists of two fixed-width, floated elements. Note that the sidebar and content area
are not the same height in this example. This is one of the tricky parts with multi-column layouts using floats, and
requires workarounds to make multiple columns appear to be the same height.

HTML:

<div class="wrapper">

<div class="sidebar">
<h2>Sidebar</h2>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio.</p>
</div>

<div class="content">
<h1>Content</h1>

<p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.
Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque
nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin
ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non,
massa. Fusce ac turpis quis ligula lacinia aliquet. </p>
</div>

</div>

CSS:

.wrapper {
width:600px;
padding:20px;
background-color:pink;

/* Floated elements don't use any height. Adding "overflow:hidden;" forces the
parent element to expand to contain its floated children. */
overflow:hidden;
}

.sidebar {
width:150px;
float:left;
background-color:blue;

GoalKicker.com – CSS Notes for Professionals 86


}

.content {
width:450px;
float:right;
background-color:yellow;
}

Section 14.7: Simple Three Fixed-Width Column Layout


HTML:

<div class="wrapper">
<div class="left-sidebar">
<h1>Left Sidebar</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p>
</div>
<div class="content">
<h1>Content</h1>
<p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.
Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque
nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin
ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non,
massa. </p>
</div>
<div class="right-sidebar">
<h1>Right Sidebar</h1>
<p>Fusce ac turpis quis ligula lacinia aliquet.</p>
</div>
</div>

CSS:

.wrapper {
width:600px;
background-color:pink;
padding:20px;

/* Floated elements don't use any height. Adding "overflow:hidden;" forces the
parent element to expand to contain its floated children. */
overflow:hidden;
}

.left-sidebar {
width:150px;
background-color:blue;
float:left;
}

.content {
width:300px;
background-color:yellow;
float:left;
}

.right-sidebar {
width:150px;
background-color:green;
float:right;
}

GoalKicker.com – CSS Notes for Professionals 87


Section 14.8: Two-Column Lazy/Greedy Layout
This layout uses one floated column to create a two-column layout with no defined widths. In this example the left
sidebar is "lazy," in that it only takes up as much space as it needs. Another way to say this is that the left sidebar is
"shrink-wrapped." The right content column is "greedy," in that it takes up all the remaining space.

HTML:

<div class="sidebar">
<h1>Sidebar</h1>
<img src="http://lorempixel.com/150/200/" />
</div>

<div class="content">
<h1>Content</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed
cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis
ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia
arcu eget nulla. </p>
<p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.
Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque
nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin
ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non,
massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper
vel, tincidunt sed, euismod in, nibh. </p>
</div>

CSS:

.sidebar {
/* `display:table;` shrink-wraps the column */
display:table;
float:left;
background-color:blue;
}

.content {
/* `overflow:hidden;` prevents `.content` from flowing under `.sidebar` */
overflow:hidden;
background-color:yellow;
}

Fiddle

GoalKicker.com – CSS Notes for Professionals 88


Chapter 15: Typography
Parameter Details
font-style italics or oblique
font-variant normal or small-caps
font-weight normal, bold or numeric from 100 to 900.
font-size The font size given in %, px, em, or any other valid CSS measurement
line-height The line height given in %, px, em, or any other valid CSS measurement
font-family This is for defining the family's name.
color Any valid CSS color representation, like red, #00FF00, hsl(240, 100%, 50%) etc.
Whether or not to use a confenced or expanded face from font. Valid values are normal, ultra-
font-stretch condensed, extra-condensed, condensed, semi-condensed, semi-expanded, expanded, extra-
expanded or ultra-expanded
text-align start, end, left, right, center, justify, match-parent
text-decoration none, underline, overline, line-through, initial, inherit;

Section 15.1: The Font Shorthand


With the syntax:

element {
font: [font-style] [font-variant] [font-weight] [font-size/line-height] [font-family];
}

You can have all your font-related styles in one declaration with the font shorthand. Simply use the font property,
and put your values in the correct order.

For example, to make all p elements bold with a font size of 20px and using Arial as the font family typically you
would code it as follows:

p {
font-weight: bold;
font-size: 20px;
font-family: Arial, sans-serif;
}

However with the font shorthand it can be condensed as follows:

p {
font: bold 20px Arial, sans-serif;
}

Note: that since font-style, font-variant, font-weight and line-height are optional, the three of them are
skipped in this example. It is important to note that using the shortcut resets the other attributes not given.
Another important point is that the two necessary attributes for the font shortcut to work are font-size and font-
family. If they are not both included the shortcut is ignored.

Initial value for each of the properties:

font-style: normal;
font-variant: normal;
font-weight: normal;

GoalKicker.com – CSS Notes for Professionals 89


font-stretch: normal;
font-size: medium;
line-height: normal;
font-family – depends on user agent

Section 15.2: Quotes


The quotes property is used to customize the opening and closing quotation marks of the <q> tag.

q {
quotes: "«" "»";
}

Section 15.3: Font Size


HTML:

<div id="element-one">Hello I am some text.</div>


<div id="element-two">Hello I am some smaller text.</div>

CSS:

#element-one {
font-size: 30px;
}

#element-two {
font-size: 10px;
}

The text inside #element-one will be 30px in size, while the text in #element-two will be 10px in size.

Section 15.4: Text Direction


div {
direction: ltr; /* Default, text read read from left-to-right */
}
.ex {
direction: rtl; /* text read from right-to-left */
}
.horizontal-tb {
writing-mode: horizontal-tb; /* Default, text read from left-to-right and top-to-bottom. */
}
.vertical-rtl {
writing-mode: vertical-rl; /* text read from right-to-left and top-to-bottom */
}
.vertical-ltr {
writing-mode: vertical-rl; /* text read from left-to-right and top to bottom */
}

The direction property is used to change the horizontal text direction of an element.

Syntax: direction: ltr | rtl | initial | inherit;

The writing-mode property changes the alignment of text so it can be read from top-to-bottom or from left-to-right,
depending on the language.

GoalKicker.com – CSS Notes for Professionals 90


Syntax: direction: horizontal-tb | vertical-rl | vertical-lr;

Section 15.5: Font Stacks


font-family: 'Segoe UI', Tahoma, sans-serif;

The browser will attempt to apply the font face "Segoe UI" to the characters within the elements targeted by the
above property. If this font is not available, or the font does not contain a glyph for the required character, the
browser will fall back to Tahoma, and, if necessary, any sans-serif font on the user's computer. Note that any font
names with more than one word such as "Segoe UI" need to have single or double quotes around them.

font-family: Consolas, 'Courier New', monospace;

The browser will attempt to apply the font face "Consolas" to the characters within the elements targeted by the
above property. If this font is not available, or the font does not contain a glyph for the required character, the
browser will fall back to "Courier New," and, if necessary, any monospace font on the user's computer.

Section 15.6: Text Overflow


The text-overflow property deals with how overflowed content should be signaled to users. In this example, the
ellipsis represents clipped text.

.text {
overflow: hidden;
text-overflow: ellipsis;
}

Unfortunately, text-overflow: ellipsis only works on a single line of text. There is no way to support ellipsis on
the last line in standard CSS, but it can be achieved with non-standard webkit-only implementation of flexboxes.

.giveMeEllipsis {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: N; /* number of lines to show */
line-height: X; /* fallback */
max-height: X*N; /* fallback */
}

Example (open in Chrome or Safari):

http://jsfiddle.net/csYjC/1131/

Resources:

https://www.w3.org/TR/2012/WD-css3-ui-20120117/#text-overflow0

Section 15.7: Text Shadow


To add shadows to text, use the text-shadow property. The syntax is as follows:

text-shadow: horizontal-offset vertical-offset blur color;

Shadow without blur radius

GoalKicker.com – CSS Notes for Professionals 91


h1 {
text-shadow: 2px 2px #0000FF;
}

This creates a blue shadow effect around a heading

Shadow with blur radius

To add a blur effect, add an option blur radius argument

h1 {
text-shadow: 2px 2px 10px #0000FF;
}

Multiple Shadows

To give an element multiple shadows, separate them with commas

h1 {
text-shadow: 0 0 3px #FF0000, 0 0 5px #0000FF;
}

Section 15.8: Text Transform


The text-transform property allows you to change the capitalization of text. Valid values are: uppercase,
capitalize, lowercase, initial, inherit, and none

CSS

.example1 {
text-transform: uppercase;
}
.example2 {
text-transform: capitalize;
}
.example3 {
text-transform: lowercase;
}

HTML

<p class="example1">
all letters in uppercase <!-- "ALL LETTERS IN UPPERCASE" -->
</p>
<p class="example2">
all letters in capitalize <!-- "All Letters In Capitalize (Sentence Case)" -->
</p>
<p class="example3">
all letters in lowercase <!-- "all letters in lowercase" -->
</p>

Section 15.9: Letter Spacing


h2 {
/* adds a 1px space horizontally between each letter;
also known as tracking */
letter-spacing: 1px;

GoalKicker.com – CSS Notes for Professionals 92

You might also like