CSS Tutorial

CSS Tutorial

Cascading Style Sheets (CSS), along with HTML markup language, HTTP protocol, and JavaScript scripting language, is one of the building blocks of the modern Internet. HTML is used for structuring documents, HTTP for transferring them between computers, JavaScript for modifying them dynamically, and CSS is used for controlling their visual aspects. In this tutorial, you will learn what is CSS and get acquainted with the parts of the CSS language that are important from a practical perspective.

What is CSS?

CSS, Cascading Style Sheets, is a computer style sheet language that controls the visual aspects of computer documents. A collection of stylistic rules through which CSS controls those aspects is called a style sheet.

CSS was first proposed in 1994 by Håkon Wium Lie who at the time was working with the creator of HTML, Tim Berners-Lee, at CERN. CSS was an extension of ideas of other style sheet languages that already existed in the 1980s and were dedicated to styling documents written in congruence with SGML (Standard Generalized Markup Language) standard.

CSS can be used to style in particular:

  • HTML documents,

  • XML documents, and

  • Scalable Vector Graphics (SVG) elements.

CSS, just like other typical style sheet languages, controls the visual aspects of supported computer documents through its set of stylistic rules that can be divided into:

  • property rules - governing the application of visual aspects to a given document element through the usage of properties,

  • selecting rules - governing the selecting of elements to which property rules should apply,

  • inheritance rules - governing the way in which property rules applicable to elements are inherited by (cascade to) their children elements.

Including CSS

There are three basic ways of including CSS into an HTML document:

  • inline,

  • internal, and

  • external.

Further, styling rules for a given HTML come also from user-agent defaults (aka user-agent style sheets) and user overrides.

Inline CSS

An inline CSS styling is placed in the style attribute of a given HTML element.

<p style="font-size: 24px; color: red">
  I like horses!
</p>

The inline CSS styling applies only to the relevant element and with regards to some properties to elements nested within it. No other elements of the HTML document are affected.

Using CSS inline styling intertwines the presentational aspects of CSS with structural aspects of HTML and therefore is discouraged in favor of internal or external CSS inclusion.

Internal CSS

The Internal CSS means placing CSS styling rules in a style element which is nested in the head element.

Internal CSS styling rules are applicable to all selected elements of an HTML document.

<!DOCTYPE html>
<html>
  <head>
    <style>
      p {
        font-size: 24px;
        color: red;
      }
    </style>
  </head>
  <body>
    <p>
      ...
    <p>
    <p>
      ...
    <p>
  </body>
<html>

The styling rules defined in the style element apply to all p elements of the presented HTML document.

External CSS

The external CSS means placing CSS styling rules in a document separated from the styled HTML document and linking it using a link element placed in the head.

The styling rules defined in the linked CSS document are applicable to all selected elements of an HTML document

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="foo.css">
  </head>
  <body>
    <p>
      ...
    <p>
    <p>
      ...
    <p>
  </body>
<html>

The external CSS files should use the *.css extension. The CSS styling rules in the external file must include selectors and applicable properties.

p {
  font-size: 24px;
  color: red;
}

CSS Inclusion Rules Precedence

A given HTML element styling rules can come simultaneously from the inline CSS, internal CSS and external CSS.

In case of a styling rule conflict inline CSS has precedence over both internal CSS and external CSS.

The precedence of internal and external CSS depends on the order of their inclusion with the last included having the highest precedence.

p {
  font-size: 28px;
  color: blue;
  text-decoration: underline;
}
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="foo.css">
    <style>
      p {
        font-size: 24px;
        color: red;
      }
    </style>
  </head>
  <body>
    <p style="font-size: 18px;">
      ...
    </p>
  </body>
<html>

The p element in the above example shall have the text that is a) underlined (from the external CSS), b) red (from the internal CSS) and c) with the font size of 18px (from the inline CSS).

<!DOCTYPE html>
<html>
  <head>
    <style>
      p {
        font-size: 24px;
        color: red;
      }
    </style>
    <link rel="stylesheet" href="foo.css">
  </head>
  <body>
    <p style="font-size: 18px;">
      ...
    </p>
  </body>
<html>

The p element in the above example shall have the text that is a) underlined (from the external CSS), b) blue (again from the external CSS) and c) with the font size of 18px (from the inline CSS).

Style Declarations

A given HTML element is styled by CSS with style declarations.

A CSS style declaration is a block of code built with property/value pairs consisting of properties, colons, values and ending semicolons. The ending semicolon is optional for the last property/value pair.

An inline CSS style declarations must not be confined within any brackets.

<p style="font-size: 24px; color: red">...</p>

Internal and external CSS style declarations must be confined within curly brackets and preceded by a selector.

p {
  font-size: 24px;
  color: red
}

The name of properties are strictly defined by CSS.

The CSS value data types are also strictly imposed by CSS. The value data types include:

  • keywords (e.g. inherit, blue),

  • integers and/or floats with units (e.g. 42px, 23%),

  • hexadecimals, RGBA, HSL, HSLA for colors.

CSS style declaration can define among others the following features of an element:

  • positioning (x-axis, y-axis and z-axis),

  • size,

  • shape,

  • borders,

  • background color and/or picture,

  • text alignment, and

  • font family and color.

When style declarations have the same specificity associated the last defined style declaration is applied.

Cascading

Relevant style declarations for a single HTML element can come among others from:

  • inline, internal and external CSS,

  • inheritance,

  • user-agent defaults (aka user-agent style sheets), and

  • user overrides.

The process of algorithmic determination of style declarations specifically applicable to a given HTML element, basing on inline, internal, external CSS, inheritance, user-agent defaults and user overrides, is called cascading.

The above-mentioned algorithmic determination process provided the foundation for the Cascading Style Sheets name.

Selectors

What is a CSS Selector?

CSS style declarations are not applicable to all HTML elements - unless the universal selector is used - but to a programmatically pointed ones.

A CSS selector programmatically points (aka selects) elements to which given CSS style declarations apply.

An HTML element can be selected by:

  • a type,

  • an id attribute,

  • a class attribute,

  • a pseudo-class attribute,

  • a relation (using combined selectors),

  • an attribute, and

  • its pseudo-element status.

The respective style declarations are added to all selected elements within a given document. However, it does not mean that the selected elements shall have the style declarations actually applied as the cascading process comes into play after the selection and after adding the style declarations.

Universal Selector

The universal selector denoted by * selects:

  • all elements within a given HTML document when used autonomously, or

  • all elements within a given element when combined with another selector using general descent combinator.

* {
  font-size: 18px;
  color: blue;
}
p * {
  font-size: 18px;
  color: blue;
}

Type Selector

The CSS type selector (aka tag selector) selects all elements within a given HTML document of a given type.

p {
  font-size: 18px;
  color: blue;
}
<body>
  <p>...</p>  <!-- selected -->
  <p>...</p>  <!-- selected -->
  <div>...</div>  <!-- not selected -->
</body>

Id Selector

There can be only one element with a given id in a given HTML document. The id CSS selector selects the HTML element with the id attribute.

To select an element by its id use the # special character appended with the id.

#foo {
  font-size: 18px;
  color: blue;
}
<body>
  <p>...</p>  <!-- not selected -->
  <p id="foo">...</p>  <!-- selected -->
  <div>...</div>  <!-- not selected -->
</body>

Attribute Selector

It is possible to select elements on the basis of the presence of a given attribute using the element[attribute] syntax. For example: a[onclick] selects only a elements with onclick attribute present.

Further, it is possible to select elements on the basis of values of their attributes. For example, a[href="https://soundof.it"] selects only a elements with href attribute with the value of https://soundof.it. Special value matchers such as *= (containing anywhere), ^= (prefixed by), $= (suffixed by), and ~= (containing in a list) can be used to match values.

Class Selector

The class CSS selector selects all HTML elements with a given class attribute.

There can be an unlimited number of HTML elements with a given class in an HTML document.

To select all elements with a given class use the . character appended with the class.

.bar {
  font-size: 18px;
  color: blue;
}
<body>
  <p class="bar">...</p>  <!-- selected -->
  <p id="foo">...</p>  <!-- not selected -->
  <div>...</div>  <!-- not selected -->
</body>

An element can have more than one class at the same time. All the element's classes are within the value of the same class attribute separated by spaces.

<p class="foo bar foobar">...</p>

Pseudo-Class Selector

A pseudo-class selector selects an element or elements having a specific pseudo-class attribute which is assigned to those elements automatically on the basis of their:

  • specific state (e.g. being hovered, focused, checked, unvisited, visited), or

  • specific structure or placement in reference to another element (e.g. being a first child or an n-th element).

A pseudo-class is denoted by a colon (:) appended with a keyword.

Specific State Pseudo-Class Selectors

The purpose of specific state pseudo-class selectors is to add style declarations to a given element or elements only when the elements are in a specific state.

The notable specific state pseudo-class selectors are:

  • :link - selects non-visited anchor elements,

  • :visited - selects visited anchor elements,

  • :hover - selects an element being hovered over,

  • :focus - selects a focused element,

  • :enabled - selects all enabled form elements,

  • :disabled - selects all disabled form elements,

  • :read-only - selects all read-only form elements,

  • :checked - selects checked form elements,

  • :required - selects required form elements

  • :optional - selects optional form elements

Specific Structure or Placement in Reference to Another Element Selectors

There is one notable specific structure selector, namely :empty. It selects all elements without any content other than spaces.

There are many specific placement in reference to other element selectors. The most notable are:

  • :only-child - selects elements being the only children of another elements,

  • :only-of-type - selects elements with specific type being the only children of another elements,

  • :first-child / :last-child - selects elements being the first / last children of another elements,

  • :first-of-type / :last-of-type - selects elements with specific type being the first / last children of another element,

  • :nth-child / :nth-last-child - uses an+b notation and selects elements being nth children (counting respectively from the beginning / end) of another elements,

  • :nth-of-type / :nth-last-of-type - uses an+b notation to select nth (counting respectively from the beginning / end) children of another elements with a specific type,

Implicit Universal Selector Before Pseudo-Classes

When no selector is provided before a pseudo-class a universal selector is implicitly added.

Therefore, p :first-child really means p *:first-child which selects all elements in a given document being the first children of p elements. This is different from p:first‑child which selects all p elements being at the same time first children of other elements.

Chaining Class & Pseudo-Class Selectors

Both class selectors and pseudo-class selectors can be chained together with each other and with other selectors to select elements more specifically.

For example:

  • p.foo - selects p elements that have the class foo at the same time (compare it to p .foo combined selector),

  • .foo.bar - selects elements having both the foo and bar classes at the same time,

  • p:first-child - selects p element that are first children of other elements (compare it to p :first-child combined selector).

Grouping (aka Listing) Selectors

It is possible to associate a given style declaration with more than one selector at the same time using selector grouping (aka listing) using the , (comma) special character.

For example:

  • div, p { ... } - associates a given style declaration with both div and p elements (compare it to div p combined selector).

  • #foo, p:first-child, .bar { ... } - associates a given style declaration with the element having the #foo id, with p elements being first children of other elements and with elements having the .bar class.

Combined Selectors

A combinator is a keyword that indicates a relation between selectors.

Combined selectors are selectors that are built with at least two other selectors joined by combinators which select elements on the basis of their relation towards other elements.

There are the following kind of combinators is CSS:

  • space - general descent relation,

  • > - direct descent (child) relation

  • ~ - general sibling relation,

  • + - direct (adjacent) sibling relation.

General Descendant Selector

The general descendant selector is a CSS selector that uses the space combinator and selects elements being direct and indirect descendants of a specific element or elements.

For example to select all p elements being direct and indirect descendants of div elements the div p general descendant selector should be used.

div p {
  ...
}
<body>
  <div>
    <p>...</p>  <!-- selected -->
    <section>
      <p>...</p>  <!-- selected -->
    </section>
  </div>
  <p>...</p>  <!-- not selected -->
</body>

Direct Descendant (Child) Selector

The direct descendant (child) selector is a CSS selector that uses the > combinator and selects elements being direct descendants (children) of a specific element or elements.

For example to select all p elements being direct descendants (children) of div elements the div > p direct descendant (child) selector should be used.

div > p {
  ...
}
<body>
  <div>
    <p>...</p>  <!-- selected -->
    <section>
      <p>...</p>  <!-- not selected -->
    </section>
  </div>
  <p>...</p>  <!-- not selected -->
</body>

General Sibling Selector

The general sibling selector is a CSS selector that uses the ~ combinator and selects elements following directly or indirectly a specific element or elements with the same parent element.

For example, to select all p elements being direct and indirect siblings of div elements the div ~ p general sibling selector should be used.

div ~ p {
  ...
}
<body>
  <div>
    <p>...</p>  <!-- not selected -->
  </div>
  <p>...</p>  <!-- selected -->
  <p>...</p>  <!-- selected -->
  <section>
    <p>...</p>  <!-- not selected -->
  </section>
</body>

Direct (Adjacent) Sibling Selector

The direct (adjacent) sibling selector is a CSS selector that uses the + combinator and selects elements following directly a specific element or elements with the same parent element.

For example, to select all p elements being direct (adjacent) siblings of div elements the div + p direct (adjacent) sibling selector should be used.

div + p {
  ...
}
<body>
  <div>
    <p>...</p>  <!-- not selected -->
  </div>
  <p>...</p>  <!-- selected -->
  <p>...</p>  <!-- not selected -->
</body>

Specificity

Simultaneously many overshadowing style rules can be associated with the same element arising out of style declarations regarding the same element due to:

  • the inclusion of those style declarations in inline, internal and external CSS, or

  • the element being selected by more than one selector at the same time (which is almost always the case).

Specificity is a set of principles that govern which of overshadowing style rules associated with a given element are ultimately applied for actual styling process.

The principles of specificity are quite intricate and their final result is indicated by four numbers (from the most important to the least important) separated by commas. For the sake of simplifying, it could be outlined that the hierarchy of specificity is as follows:

  • inline CSS,

  • id selectors,

  • chained class & pseudo-class selectors,

  • class selectors,

  • combined selectors,

  • tag selectors.

Style rules declared using inline CSS have the specificity of 1,0,0,0.

The outcome specificity for style rules associated with given selectors is as follows:

  • an id selector (e.g. #foo) - 0,1,0,0,

  • a class selector chained with another class selector (e.g. .foo.bar) - 0,0,2,0,

  • a tag selector chained with a class selector (e.g. p.foo) - 0,0,1,1,

  • a class selector (e.g. .foo) - 0,0,1,0,

  • a combined two tag selector (e.g. div p) - 0,0,0,2,

  • a tag selector (e.g. p) - 0,0,0,1.

Inheritance

What is CSS Inheritance?

As outline in the above chapters, style rules are associated with elements through usage of inline CSS and/or through usage of internal/external CSS together with selectors. In addition to that, style rules are being associated with elements through inheritance.

In CSS, inheritance is a mechanism of associating style rules that are applied to a given ancestor element to the descendants of that element in the document tree (a given element A is considered to be descendant of another element B when the element A is nested in the element B).

Inheritance of Text-Related Properties

Generally, the text-related properties are inherited.

The inherited properties include in particular:

  • visibility,

  • text-align,

  • text-indent,

  • text-transform,

  • word-spacing,

  • letter-spacing,

  • white-space,

  • line-height,

  • font,

  • color, and

  • list-style.

Non-Inheritance of Box-Related Properties

Generally, the box-related properties are not inherited.

The non-inherited properties include in particular:

  • display,

  • position,

  • z-index,

  • margin,

  • float,

  • clear,

  • width,

  • max-width,

  • min-width,

  • height,

  • max-height,

  • min-height,

  • outline,

  • border,

  • padding,

  • background,

  • overflow,

  • vertical-align,

  • text-decoration (a text related property).

Controlling Inheritance

It is possible to expressly indicate whether a given property should be inherited or not by using the following keywords:

  • inherit - sets the property as inheritable irrespective of its default behavior,

  • initial - sets the property value to its default value specified in the CSS specifications (not browser defaults - vide What is use of 'initial' value in CSS?),

  • unset - sets the property inheritability to the one specified in CSS specifications (i.e. its default inheritability as outlined in the above chapters), and

  • revert - sets the property value to the browser's default.

For example:

p {
  overflow: inherit;
}

Box Model

What is the CSS Box Model?

The box model is a rule stating that each element in CSS is displayed as a box with a controllable:

  • sizing,

  • outer and inner display, and

  • position.

Each element's box is comprised of its:

  • content,

  • padding,

  • border, and

  • margin.

Box Sizing

What is Box Sizing?

The box-sizing is a property that governs how width, height, margin, border and padding properties impact the actual visual dimensions of a given element.

The box-sizing property can be set to:

  • content-box, or

  • border-box.

The third known box-sizing value is padding-box which is however as of now unsupported by most browsers.

In both - content and border box - models margin is not included in the width and height properties but still affects the actual space claimed by a given element.

Content Box

The default value of the box-sizing property of most HTML elements is content-box.

In content box model the width and height properties control only the element's content width and height and therefore padding and border increase the actual visual dimensions of the element box.

Border Box

The box-sizing property can be set to border-box instead of content-box.

In border box model the width and height properties control the element's content, padding and border width and height jointly.

Some HTML elements like table, select, button, radio input and checkbox input have the box-sizing property set to border-box by default.

To set all elements box-sizing property to border-box:

html {
  box-sizing: border-box;
}

*, *::before, *::after {
  box-sizing: inherit;
}

Margin

What is a Margin?

A margin is a space around an element box. It is not included in width nor height irrespective of the box-sizing value.

Margins can have both positive and negative values.

Controlling Margin

It is possible to control top, right, bottom, left margins simultaneously using the margin property or control each of the particular side margins using margin-top, margin-right, margin-bottom and margin-left.

p {
  margin: 15px 10px 5px 0; /* top 15px, right 10px, bottom 5px and left 0 */
}

p  {
  margin-top: 15px;
  margin-right: 10px;
  margin-right: 5px;
  margin-left: 0;
}

p {
  margin: 15px; /* top, right, bottom and left 15px */
}

p {
  margin: 15px 10px; /* top and bottom 15px, right and left 10px */
}

p {
  margin: 15px 10px 5px; /* top 15px, right and left 10px, bottom 5px */
}

Margin Collapsing

When top and bottom margins from two sibling non-floating and non-absolutely positioned element boxes meet they collapse into each other in the following manner:

  • when both margins are positive the one furthest from zero is applied,

  • when both margins are negative also the one furthest from zero is applied,

  • when one margin is positive and one negative they are subtracted from each other.

Further, the top margin of a child element can collapse outside of the parent element when there is nothing before the child element. Similar behavior applies to the bottom margin.

Border

What is a Border?

The border in the CSS box model is a line between the margin and the padding.

In the content-box model the border is not included in width and height.

In the border-box model the border is included in width and height.

Controlling Border

It is possible to control width, style and color properties of a border simultaneously using the border property or control each of them separately using border-style, border-width and border-color properties.

It is possible to control top, right, bottom, left borders simultaneously using the border property or control each of the particular side margins using border-top, border-right, border-bottom and border-left.

The border-width, border-style and border-color properties can be combined with border-top, border-right, border-bottom and border-left to target particular property and side, e.g. border-top-width.

p {
  border: 1px solid red;
}

p {
  border-width: 1px;
  border-style: solid; /* none, dotted, inset, dashed, double, groove */
  border-color: red;
}

p {
  border-style: solid;
  border-color: green;
  border-top: 2px solid blue;
  border-right: 5px dotted gray;
  border-bottom-width: 10px;
}

Padding

What is Padding?

Padding in the CSS box model is a space between the content and the border.

In the content-box model padding is not included in width and height.

In the border-box model padding is included in width and height.

A padding property can only have non-negative values.

Controlling Padding

It is possible to control top, right, bottom, left paddings simultaneously using the padding property or control each of the particular side paddings using padding-top, padding-right, padding-bottom and padding-left.

p {
  padding: 42px;
}

div {
  padding-top: 23px;
}

Width & Height

The width and height properties control respectively how much horizontal and vertical space a given element box claims.

In content-box model a border and padding are not included in width and height.

In border-box model a border and padding are included in width and height.

A margin is never included in width and height irrespective of whether content-box model or border-box model is applied.

p {
  width: 84px;
  height: 42px;
}

Outer Display

What is an Outer Display?

The outer display property denoted by the keyword display is a property that controls how a given box is visually presented (displayed) in relation to its ancestor element and its sibling elements.

The outer display property can have the following values:

  • block,

  • inline-block, and

  • inline.

.abc {
  display: block;
}

In HTML some elements have display set to block by default and are known as non‑phrasing elements and some have display set to inline and are known as phrasing elements. See HTML Tutorial: Non-Phrasing v. Phrasing Content Elements for more details on the subject.

It is allowed to nest inline elements within block elements but it is not allowed to nest block elements within inline elements.

Block Display

An element with display property set to block:

  • breaks onto a new container line,

  • takes as much of the container line's space as available to it unless its width does not require it,

  • has their width and height properties respected.

Inline-Block Display

An element with display property set to inline-block:

  • does not break onto a new container line,

  • takes only as much of the container's line or lines as is necessary due to its content or width,

  • has its width, height, margin, and padding properties respected.

Inline Display

An element with display property set to inline:

  • does not break onto a new container line,

  • takes only as much of the container's line or lines as is necessary due to its content,

  • has its width, height and vertical margin and padding properties not respected but horizontal margin and padding properties respected.

Inner Display

What is an Inner Display?

The inner display property denoted by the keyword display (just like the outer display) is a property that controls how statically and relatively positioned descendant elements of a given element are visually presented (displayed) within it and in relation to it and each other.

By default elements within an element with the display property set to block, inline-block or inline are presented due to the rules outlined above for the outer display which might be referred to as the normal flow. However, the display property can also be set to flex or grid (inline-flex or inline-grid alternatively) which sets the outer display to block (inline alternatively) but changes the inner display to respectively flex or grid behavior.

Flex

Descendant elements of an element that has its display property set to flex are automatically spatially unidirectionally (unidimensionally) - horizontally or vertically - arranged depending upon a container width and height.

Grid

Descendant elements of an element that has its display property set to grid are automatically spatially two‑directionally (two‑dimensionally) - horizontally and vertically - arranged depending upon a container width and height.

Position

What is Position?

The CSS the position property controls the manner in which a given element box is placed in a document.

The position property can have the following values:

  • static,

  • relative,

  • absolute,

  • fixed, and

  • sticky.

Non-statically positioned elements are sometimes referred to as positioned elements.

Static Position

In HTML by default all elements have the position property initial value of static.

The static positioning of an element means positioning pursuant to the normal flow of the document which means that the element takes space in the document in congruence with the outer and inner display rules and without any visual offset.

When an element is statically positioned the top, right, bottom, left and z-index properties have no effect on the element.

Relative Position

The relative positioning of an element means allocating a space for that element in the document in congruence with the outer and inner display rules but allowing a visual offset in relation to the allocated space using the top, right, bottom and left properties. The offset does not impact the allocated space and the flow for other element boxes.

Setting the position value to relative creates a new stacking context and thus enables stacking with z-index property for that element box.

Absolute Position

The absolute positioning of an element means not allocating a space for that element in congruence with the normal flow (i.e. with congruence with the outer and inner display rules) but placing that element in relation to its closest non-statically positioned ancestor (using the top, right, bottom and left properties) or in the absence of such an ancestor the initial containing block.

The collapsing of margins does not take place for absolutely positioned element boxes.

Setting the position value to absolute creates a new stacking context and thus enables stacking with z-index property for that element box.

The width and height properties for the absolutely positioned element boxes can be set in particular to auto, _px and _%.

Fixed Position

The fixed positioning of an element means not allocating a space for that element in congruence with the normal flow (i.e. with congruence with the outer and inner display rules) but placing that element in relation to the nearest ancestor with the transform, perspective or filter property value other than none or in the absence of such an element the viewport.

Setting the position value to fixed creates a new stacking context and thus enables stacking with z-index property for that element box.

Sticky Position

The sticky positioning of an element is a relative positioning of that element until a certain scrolling threshold is met when the positioning changes to fixed but only within the scrolling boundaries of its nearest block displayed ancestor.

Setting the position value to sticky creates a new stacking context and thus enables stacking with z-index property for that element box.

Z-Index

With the position property it is possible to specify a placement in a document horizontally and vertically i.e. x‑index (abscissa) and y‑index (ordinate). The z‑index (applicate) property allows for specifying for non‑statically positioned or flexed element boxes the stack order i.e. which one box should visually appear on top of another.

For a given element box the z-index property specifies the stack level through usage of both negative and positive integers. The higher the value the higher the stack level. An element box with a higher stack level appears visually over elements with lower stack level.

When an element has the z-index property set to other value than the default auto it establishes a new local stacking context for its ancestors. When comparing stack levels local stacking context levels of elements are taken into account before stacking levels of particular elements.

.class_a {
  position: relative;
  z-index: 2;
}

.class_b {
  position: relative;
  z-index: 1
}

Text Styling

What is Text Styling?

Text styling in CSS is adjusting text content of a given element through specifying the text content's:

  • font,

  • color,

  • alignment,

  • underlining & striking through with decorative line,

  • letter casing,

  • line height,

  • word and letter spacing,

  • handling white space and line breaking,

  • shadow.

Font

Font Styling Aspects

A font of a given text content can be styled in the following aspects:

  • family,

  • size,

  • weight (bolding),

  • variant (non-small-caps vs small-caps), and

  • style (italicization).

Font Family

CSS allows for specifying a font for an element's text content using the font-family property.

Not always a specified font is available on all client devices. Therefore, a value of a font-family property should include more than one font name simultaneously. The consecutively provided fonts serve as fallbacks in case of absence on a client device of previously specified ones. Therefore, the last provided one should be a generic like serif, sans-serif or monospace.

p {
  font-family: "Times New Roman", serif;
}

Multi-word font names need to be included in quotation marks.

There are three primary families of fonts:

  • serif (with letter ending small strokes) e.g. Times New Roman, Garamond,

  • sans-serif (without letter ending small strokes) e.g. Arial, Helvetica, and

  • monospace (with equal-width letters often used for presenting code syntax) e.g. Courier.

Each of the provided primary font family names can be used as a generic fallback at font-family property.

Some fonts, like the mentioned Times New Roman or Arial, are considered a web safe fonts i.e. generally available on client devices.

Font Size

It is possible to specify a font size of a given text content using the font-size property.

p {
  font-size: 18px;
}

There are several size units that can be used to express a font-size value.

The most often used font size units are the ones that relatively (i.e. non‑absolutely) specify the font size. The most prominent of those are:

  • px - screen pixels,

  • em - relative to the current font size of a given element in pixels,

  • rem (root em) - relative to the font size of the root element of a given document in pixels, and

  • vh (viewport width) - where 1vh means 1% of a viewport width.

The default font size in most browsers is 16px.

In addition to relative font size units it is possible to specify font size absolutely in inches (in), centimeters (cm), points (pt) and pica (pc) where 1 inch = 2.54 centimeters = 72 points = 6 pica.

Using relative units over absolute units for text content dedicated to be displayed on client devices of varying screen sizes such as desktop and laptop computers, smartphones, and tablets allows for user text resizing and therefore is considered a good practice.

Font Boldness

The font-weight property allows for specifying boldness (thickness) of text content through using:

  • keywords - normal for unbolded text and bold for bolded text,

  • numeric values from 100 to 950 where the normal keyword equates 400 and the bold keyword equates 700.

p {
  font-weight: bold;
}

div {
  font-weight: 200;
}

Font Italicization

It is possible to italicize text content using the font-style property. The properties values are normal for non‑italicized text and italic for italicized text.

p {
  font-style: italic;
}

Font Small Capitalizing

To present text content as small capitalized letters use the font-variant property and the keyword small-caps.

p {
  font-variant: small-caps;
}

Text Color

To specify text content color use the color property. The color can be specified using:

  • RGB color values,

  • hexadecimal color values,

  • HSL color values, or

  • predefined color names.

p {
  color: red;
}

Check out the chapter on colors to learn more.

Text Alignment

Horizontal Text Alignment

To horizontally align text content and nested inline and inline-block elements use text-align property.

The text and nested inline and inline-block elements can be:

  • left aligned (left),

  • centered (center),

  • right aligned (right), and

  • justified (justify).

p {
  text-align: center;
}

Vertical Text Alignment

To vertically align text content and nested inline and inline-block elements use vertical-align property.

The text and nested inline and inline-block elements can be vertically aligned to:

  • baseline (baseline),

  • top (top),

  • middle (middle), and

  • bottom (bottom).

p {
  vertical-align: middle;
}

Underlining & Striking Through with Decorative Line

It is possible to add a decorative line to text content using the text-decoration- properties specifying text-decoration-line (e.g. underline, line-through), text-decoration-color, text-decoration-style (e.g. solid, dotted) and text-decoration-thickness. The text-decoration-thickness property has limited support.

To underline text:

p {
  text-decoration-line: underline;
  text-decoration-color: red;
  text-decoration-style: solid;
  text-decoration-thickness: 2px;
}

/* Shorthand: */
p {
  text-decoration: underline red solid 2px;
}

However, the text-decoration property is often used with specifying only the line having the remaining properties resort to defaults i.e. color being set to the color of the text, style to solid and thickness to 1px.

p {
  text-decoration: underline;
}

To strike through text:

p {
  text-decoration: line-through;
}

Uppercasing & Lowercasing

To uppercase or lowercase text content use the text-transform property.

.foo {
  text-transform: uppercase;
}

.bar {
  text-transform: lowercase;
}

Line Height

To specify the height of lines of text content use the line-height property.

It's values can be expressed in:

  • numeric multiplier of the current line height, e.g. 1, 1.2, 1.5, 2,

  • the keyword normal equaling the numeric multiplier of 1,

  • other size units, e.g. px, em.

p {
  line-height: 1.5;
}

Word & Letter Spacing

To specify distance between words use the word-spacing property.

To specify distance between letters use the letter-spacing property.

The values of both spacing properties can be expressed in any unit sizes, e.g. px, em.

p {
  word-spacing: 12px;
  letter-spacing: 0.5px
}

Handling White Space & Line Breaking

To specify how white space is handled and how lines are broken use the white-space property.

Text Shadow

It is possible to add a shadow to text content using the text-shadow property.

It is possible to specify:

  • horizontal shadow size,

  • vertical shadow size,

  • blur size (optional), and

  • color (optional).

p {
  text-shadow: 2px 4px 3px #00000042;
}

We use cookies and similar technologies to enhance the quality of services, maintain statistics and adjust marketing content. You will find more information in the Cookies Policy.

By clicking OK you grant consent to processing of your personal data by us and our Trusted Partners with the purpose of maintain statistics and adjustment of the marketing content pursuant to the Privacy Policy. If you wish to not grant that consent and/or limit its extent click Settings.