Introduction to CSS

user

Michal Drobny

Mar 16, 2024

14 min read

Web development

Share this:

blog

Design plays a crucial role in the development of web applications. Styling HTML is essential to enhancing visual appeal and making the design captivating. This necessity led to Cascading Style Sheets (CSS), a technology designed to furnish HTML with style since 1996.

Over the years, CSS has evolved, expanding its capabilities to the extent that creating interactive and complex designs is now possible. An intriguing example of CSS's versatility is the development of games using solely CSS and HTML, showcasing the robust potential of CSS in web development.

The following article provides an insightful overview of CSS, covering its fundamental syntax and offering guidance on incorporating it into your projects.

Example of a game developed solely in CSS and HTML:

CSS and HTML Game Example on CodePen.

Syntax

The syntax of CSS (Cascading Style Sheets) is straightforward and designed to be easy to learn and use. It consists of a series of rules, each composed of a selector and a declaration block.

Selector      Declaration         Declaration
   │                │                 │
   ▼                ▼                 ▼                	
  span    {  font-size: 12pt;    color: white;   }
                  ▲       ▲         ▲      ▲ 
                  │       │         │      │
              Property  Value   Property  Value    

As explained previously, CSS syntax consists of several elements:

  • Selector: This part identifies the HTML element(s) you want to style. Selectors can range from simple (targeting elements by tag name, class, or ID) to complex (using combinations of selectors to target elements based on their attributes, state, or position in the document).
  • Declaration Block: The declaration block contains one or more declarations separated by semicolons. Each declaration includes a property and a value, separated by a colon. The property is the aspect of the element you want to style (such as color, font-size, border, etc.), and the value specifies the desired effect (such as red, 12px, solid black, etc.).

This approach allows for clear, organized, and intuitive styling instructions, enabling developers to create visually appealing and structured web pages.

The distinction in syntax lies solely in declaring CSS—whether directly within an HTML tag, inside a <style> tag, or in a separate CSS file.

CSS in HTML tag

When CSS is applied directly within an HTML element through the style attribute, there's no need to define a selector, as the tag itself inherently specifies the target of the styling. This method of inline CSS is exclusive to the tag it's declared on and does not impact any other HTML elements.

<p style="color: blue; font-size: 16px;">This paragraph text is styled directly without needing a selector.</p>

CSS in <style> tag

When incorporating CSS within a <style> tag, it's mandatory to specify both the selector and the declaration. This tag can be positioned in the <head> or the <body> section of the HTML document. However, adhering to best practices, placing it in the <head> section is recommended to distinguish the styling from the content.

<!DOCTYPE html>
<html>
<head>
    <!-- Best practice: Include <style> tag in the <head> section -->
    <style>
        /* CSS selector for <h1> elements */
        h1 {
            color: red;
            font-size: 24pt;
        }
        
        /* CSS selector for <p> elements */
        p {
            color: #008000;
        }
    </style>
</head>
<body>
    <h1>This is a heading styled with CSS in the <style> tag.</h1>
    <p>This paragraph is styled with CSS in the <style> tag.</p>
</body>
</html>

CSS in file

The final and most frequently utilized method involves storing your CSS in a distinct file and linking it to your HTML document. This approach detaches the styling from the HTML content, making it reusable across various HTML files or templates.

To illustrate this principle, consider having a style.css and an index.html file. The style.css file holds the CSS responsible for the visual layout of our web application, while the index.html file comprises the actual web application. Here, the organization of the files would be as follows:

h1 {
    color: red;
    font-size: 24pt;
}

p {
    color: #008000;
}

File index.html will look like this:

<!DOCTYPE html>
<html>
<head>
    <!-- Linking external CSS file for consistent styling across web pages -->
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Heading Styled with External CSS</h1>
    <p>Paragraph styled with External CSS</p>
</body>
</html>

Each style declaration adheres to a distinct process of inheriting style attributes determined by its position in the hierarchy. The section dedicated to inheritance will explain more about how this mechanism operates within CSS.

Selectors

A CSS selector is a pattern used to select the elements on a web page that you want to style with CSS. CSS selectors enable web developers to target HTML elements based on their name, id, class, attributes, and position or relation to other elements.

Selectors are divided into 5 categories:

  • Simple selectors
  • Combinator selectors
  • Pseudo-class selectors
  • Pseudo-elements selectors
  • Attribute selectors

Simple selectors

A simple CSS selector is a type of selector used to target HTML elements based on a single characteristic, such as their type tag, class, or ID. These selectors are fundamental to CSS and provide a straightforward way to apply styles to elements directly.

Simple selector types:

Selector Example Description
element p Selects all <p> alements
#id #name Selects the element with id=“name”
.class .header-menu Selects all elements with class="header-menu"
element.class p.header-menu Selects all <p> elements with class="header-menu"
* * Selects all elements
element, element p, span Selects all <p> and <span> elements

This article will concentrate on simple selectors to help readers grasp selectors fundamentally. For more comprehensive details on other types of selectors, w3schools.com offers further resources.

Element Selector

/* Selects all <p> elements */
p {
    color: blue;
}
<p>This paragraph will be blue.</p>

ID Selector

/* Selects the element with id="name" */
#name {
    font-size: 20px;
}
<div id="name">This div will have a font size of 20px.</div>

Class Selector

/* Selects all elements with class="header-menu" */
.header-menu {
    background-color: yellow;
}
<div class="header-menu">This div will have a yellow background.</div>

Element.Class Selector

/* Selects all <p> elements with class="header-menu" */
p.header-menu {
    text-align: center;
}
<p class="header-menu">This paragraph will be centered.</p>

Universal Selector

/* Selects all elements */
* {
    margin: 0;
    padding: 0;
}

This CSS rule will reset the margin and padding for all elements in the HTML document, a common practice for starting a stylesheet to ensure consistent spacing across different browsers.

Grouping Selector

/* Selects all <p> and <span> elements */
p, span {
    color: red;
}
<p>This paragraph will be red.</p>
<span>This span will also be red.</span>

Each of these examples illustrates how to use the respective simple CSS selector to target and style HTML elements based on their type, ID, class, or a combination thereof and how to apply a style universally or to a group of elements.

Inheritance

Inheritance in CSS is a fundamental principle that controls how property values of parent elements are passed down to their children. This mechanism allows certain CSS properties to influence not just the specified element but also its children, ensuring a consistent look and feel across related elements without explicitly defining styles for each one.

How Inheritance Works

  • General Principle: Not all CSS properties inherit by default. Properties related to text presentation, such as color, font-family, and font-size, inherit because it makes logical sense for text styling to be consistent throughout the content hierarchy. Other properties, especially those related to box model like margin, border, padding, and width, do not inherit because inheriting these values could lead to unexpected layouts.
  • Overriding Inheritance: Inheritance can be overridden. If a child element explicitly specifies a value for an inherited property, the child's value takes precedence over the inherited value. The inherit keyword can also force inheritance for properties that don't do so naturally.

Inheritance and Different Ways to Apply CSS

  • Inline Styles (style attribute): Styles applied directly to an HTML element using the style attribute have the highest specificity and thus override inherited styles and styles declared in <style> tags or external CSS files. Inline styles apply only to the element they are directly attached to and do not inherit to child elements unless the property naturally inherits and no other declaration has overridden it.

  • Internal Styles (<style> tag): When CSS is included within a <style> tag in the HTML document, inheritance works by applying styles to elements that match the selectors specified within the <style> tag. Child elements inherit property from parent elements unless a more specific rule in the <style> tag applies.

  • External Styles (linked CSS files): CSS defined in external stylesheets is linked to HTML documents through the <link> element. Inheritance works similarly to internal styles—the styles are applied according to the selectors that match specific elements, and children inherit properties from their parent elements, subject to the same rules of specificity and override.

To illustrate the concept of inheritance in CSS, let's create an example that demonstrates how certain properties like color, font-family, and font-size are inherited by child elements from their parent and how this inheritance can be overridden.

HTML Structure

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css">
    <style>
        /* Internal style */
        body {
            color: darkblue; 
            font-family: Arial, sans-serif; 
        }
        
        .override {
            color: red; 
            font-size: 20px; 
        }
    </style>
</head>
<body>

    <p>This paragraph inherits the body's color and font-family.</p>
    
    <div>
        This div also inherits the body's color and font-family.
        <p class="override">This paragraph has overridden the inherited color and font size.</p>
    </div>

</body>
</html>

External CSS (style.css)

body {
    font-size: 16px;
}

Explanation

  • The body tag has been styled with color, font-family, and font-size properties. According to the principles of CSS inheritance, these styles will be inherited by all child elements unless otherwise specified. This means that unless a child element has a more specific rule applied to it (either through a different CSS rule targeting it directly or through an inline style), it will display text in darkblue color, with the Arial, sans-serif font-family, and a font size of 16px as set in the external stylesheet.

  • The <p> tag directly within the body will inherit the body's styles and display text accordingly.

  • The <div> tag also inherits the body's styles, and so does its child text. However, it contains a <p> tag with the class .override, explicitly styled to have a red color and 20px font size. This demonstrates overriding inheritance: the .override class's styles take precedence over the inherited styles from the body, illustrating how specific rules can alter the inherited styles for child elements.

This example encapsulates the essence of CSS inheritance and how it can be utilized and overridden in web design for efficient styling across web pages.

Specificity

The priority of CSS rules, also known as CSS specificity, determines which styles are applied when multiple style declarations exist for the same element. This priority can vary based on where the CSS is defined: directly in an HTML tag's style attribute, within a <style> tag in the HTML document, or in an external CSS file linked to the HTML document. Here's how the priority works from highest to lowest:

  1. Inline Styles (style attribute): Styles applied directly to an element through its style attribute has the highest priority. This styling method is specific because it directly targets a single element, overriding any other styles declared in <style> tags or external CSS files for that element.

  2. Internal or Embedded Styles (<style> tag): CSS rules defined within a <style> tag in the HTML head or body come next in terms of specificity. If there are conflicting styles for an element, and none are applied directly via the style attribute, the styles in the <style> tag will take precedence over those in external CSS files. The order of the rules in the document can also affect specificity; later rules will override earlier ones if they have the same specificity level.

  3. External Styles (Linked CSS Files): Styles defined in external stylesheets linked to the HTML document have the lowest priority among these three methods when conflicts arise. Similar to internal styles, if there are multiple external stylesheets, the order in which they are linked in the HTML document matters. The styles in the last linked stylesheet will override those in earlier ones, given the same level of specificity.

Let's use a simple example to explain CSS specificity. Consider an HTML page with a paragraph element that we want to style in three ways: an inline style, an internal style within a <style> tag, and an external CSS style. Our goal is to change the color of the text in the paragraph.

HTML Structure

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css">
    <style>
        p { 
	        color: green; 
        }
    </style>
</head>
<body>
    <p id="example" class="text-style" style="color: blue;">This is a paragraph.</p>
</body>
</html>

External CSS (style.css)

p { 
	color: red; 
}

.text-style { 
	color: orange; 
}
#example { 
	color: purple; 
}

CSS Specificity Explanation

  1. Inline Style: The style attribute directly on the <p> tag sets the color to blue. Inline styles have the highest specificity, so if this rule exists, it will likely override other conflicting styles.

  2. Internal Style: Inside the <head>, we have a <style> tag that also attempts to set the paragraph's color, this time to green. This rule has a medium level of specificity. It's more specific than external styles but less specific than inline styles.

  3. External Styles:

    • The external CSS file attempts to set the paragraph color to red using a type selector (p), orange using a class selector (.text-style), and purple using an ID selector (#example).
    • The ID selector has the highest specificity, so purple normally precedes other selectors in the CSS file.
    • However, because the inline style declaration directly on the element has the highest specificity, it overrides the external and internal styles.

Result Despite the various attempts to set the paragraph's color through external, internal, and inline styles, the inline style (color: blue;) prevails due to its highest specificity. Therefore, the text in the paragraph will be blue.

This example illustrates how CSS specificity works in practice. Inline styles have the highest specificity, followed by ID selectors, class selectors, and type selectors, in that order. Remember, when multiple rules have the same specificity, the last one declared in the CSS takes precedence.

Usage

Basic Example

Here's a simple example of styling a web article, incorporating basic CSS techniques for readability. This version streamlines the CSS to focus on essential styles.

External CSS (style.css)

body {
    font-family: Arial, sans-serif;
    margin: 20px;
}

article {
    max-width: 600px;
    margin: auto;
    background-color: #f9f9f9;
    padding: 15px;
}

h1 {
    color: #333;
}

p {
    margin-bottom: 10px;
}

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Simple CSS Article Example</title>
</head>
<body>
    <article>
        <h1>Article Heading</h1>
        <p>This paragraph introduces the topic of the article. It's designed to engage the reader and provide a brief overview of the following content.</p>
        <p>Additional information is provided here to delve into the topic further, offering insights and expanding on the initial overview.</p>
    </article>
</body>
</html>

This basic example focuses on core aspects of web article styling, including font choice and margins. The CSS and HTML are pared down to illustrate a straightforward approach to creating an aesthetically pleasing and accessible article layout.

Complex Example

Building on the foundational examples, let's create a more complex scenario for styling an article using external CSS. This example will include using CSS selectors, pseudo-classes, and media queries to enhance a web article’s readability and visual appeal, demonstrating a more sophisticated application of CSS.

External CSS (style.css)

/* Base styles */
body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    line-height: 1.6;
    margin: 20px;
}

article {
    max-width: 800px;
    margin: auto;
    background-color: #f4f4f4;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

h1, h2 {
    color: #333;
}

p {
    margin: 10px 0;
}

/* Link styles */
a {
    color: darkblue;
    text-decoration: none;
}

a:hover {
    text-decoration: underline;
}

/* Navigation styling */
nav {
    margin-bottom: 20px;
    background: #333;
    color: #fff;
    padding: 10px;
    border-radius: 5px;
}

nav a {
    color: #fff;
    margin: 0 10px;
}

/* Utilizing pseudo-classes for interactive elements */
button {
    background-color: darkblue;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: navy;
}

/* Media query for responsive design */
@media (max-width: 600px) {
    article {
        margin: 10px;
        padding: 10px;
    }

    nav {
        text-align: center;
    }

    nav a {
        display: block;
        margin: 5px 0;
    }
}

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Complex CSS Example</title>
</head>
<body>
    <nav>
        <a href="#">Home</a>
        <a href="#">About</a>
        <a href="#">Contact</a>
    </nav>
    <article>
        <h1>Main Heading of the Article</h1>
        <p>This paragraph serves as an introduction to the article. It sets the stage for the detailed discussion that follows.</p>
        <h2>Subsection Heading</h2>
        <p>Here is some more detailed information, expanding on the introduction and delving into specifics.</p>
        <button>Click Me</button>
        <p>For further reading, visit <a href="#">this link</a>.</p>
    </article>
</body>
</html>

In this example, various CSS techniques enhance a web article's design. Base styles improve readability, while hover effects optimize navigation and links for user interaction. Buttons are made more interactive with color changes on hover. A media query enhances responsiveness for smaller screens, adjusting layout elements accordingly.

Conslusion

In summary, this introduction to CSS underscores its essential role in enhancing web applications’ visual appeal and functionality. CSS's evolution has broadened its capabilities, enabling the creation of sophisticated designs, as exemplified by games developed using only CSS and HTML. The article covered CSS syntax, application methods, and fundamental concepts like selectors, inheritance, and specificity.

Through examples, it demonstrated how CSS allows for precise styling control, from applying styles directly within HTML elements to leveraging external stylesheets for a consistent design across web pages. Understanding these principles is crucial for developing aesthetically pleasing and user-friendly interfaces. For those keen to expand their CSS knowledge, additional resources and in-depth guides are available online, such as on w3schools.com.