Introduction to CSS
What is CSS?
CSS, or Cascading Style Sheets, is a style sheet language used to control the presentation and layout of web pages. It works in conjunction with HTML, which is responsible for structuring content, by providing the visual and design aspects that make a website appealing and user-friendly.
How CSS Works
While HTML defines the structure and content of a webpage—such as headings, paragraphs, and images—CSS defines how this content is displayed. CSS allows you to specify colors, fonts, spacing, and even complex layouts that adapt to different screen sizes and devices.
Example:
In HTML, you might define the content like this:
Without CSS, the browser will display this content in its default style, which is usually very plain. By adding CSS, you can change the appearance of this content:
h1 {
color: darkblue;
font-size: 36px;
text-align: center;
}
p {
font-family: 'Arial', sans-serif;
color: gray;
line-height: 1.6;
}
With the above CSS, the <h1> element will now appear in dark blue, centered, and with a larger font size, while the paragraph (<p>) will be styled with a specific font, text color, and line spacing.
Cascading Nature of CSS
The “Cascading” in CSS refers to how styles are applied. CSS rules “cascade” from the top of the file to the bottom, meaning that when there are conflicting styles, the last one in the file generally takes precedence. Additionally, CSS uses a system of specificity and inheritance to determine how styles are applied, allowing for flexible and efficient design control.
Example of Cascading:
/* General rule for all paragraphs */
p {
color: black;
}
/* More specific rule that overrides the general rule */
p.special {
color: red;
}
In this example, paragraphs with the class special will be red, overriding the general rule that sets all paragraphs to black.
The Role of CSS in Web Design
CSS is essential for creating visually engaging and responsive websites. It allows designers and developers to separate content from design, making it easier to maintain and update websites. With CSS, you can control:
- Layout: Position elements on the page, create grids, and design responsive layouts that work on various screen sizes.
- Typography: Define font styles, sizes, and spacing to enhance readability.
- Colors and Backgrounds: Set background colors, images, and gradients to create visually appealing designs.
- Animation and Transitions: Add interactivity and motion to elements, enhancing user experience.
In summary, while HTML provides the structure, CSS is what brings a website to life with design, ensuring that it is not only functional but also visually appealing and consistent across different devices and browsers.
User Agent Stylesheet
When you write HTML and display it “raw” in a browser, there is already some styling (headings, fonts, margins, etc.), but this is because the browser has a standardized and predefined starting point called the user agent stylesheet. When you write your own CSS, you either overwrite or add to this stylesheet, customizing the appearance of your web pages beyond the default styles.
Syntax
Fundamentally, CSS consists of a collection of elements divided into two things:
- A selector (search definition) that tells the browser which DOM elements to affect.
- Properties that tell the browser how to affect them.
CSS syntax is straightforward but crucial for applying styles correctly to your HTML elements. Understanding how to properly structure your CSS code ensures that your styles are applied as intended, and it makes your code more readable and maintainable.
Basic Structure
In CSS, a selector is followed by a pair of curly braces {}. Inside these braces, you define the style rules by specifying properties and their corresponding values. Each property-value pair should end with a semicolon ; to separate it from the next rule.
Example:
Let’s apply this to a real-world example:
In this example:
- h1 is the selector, targeting all <h1> elements on the page.
- color: navy; is a property-value pair that sets the text color to navy.
- font-size: 24px; sets the font size to 24 pixels.
- text-align: center; centers the text within its container.
Importance of Semicolons and Curly Braces
The semicolon ; at the end of each property-value pair is important because it tells the browser where one rule ends and the next begins. Omitting a semicolon can cause the browser to misinterpret your CSS, potentially leading to unexpected results.
Example Without a Semicolon:
In this example, the missing semicolon after color: navy might cause the browser to ignore the font-size rule or not apply the styles correctly.
White Space, Tabulation, and Line Breaks
CSS is flexible with white space, meaning that the browser doesn’t care about extra spaces, tabs, or line breaks. These elements are purely for the developer’s convenience to make the code more readable and organized.
Example:
/* Readable CSS with line breaks and indentation */
p {
margin: 10px;
padding: 20px;
background-color: lightgray;
}
The same CSS can be written without any spaces or line breaks:
Both examples will produce the same result in the browser, but the first version is easier for humans to read and understand, while the second is optimized for file size.
Minification
Minification is the process of removing unnecessary spaces, line breaks, and comments from your CSS code to reduce the file size. This is particularly important for performance optimization, especially on large websites, as smaller files load faster.
Example of Minified CSS:
Original CSS:
/* Original CSS with spaces and comments */
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
h1 {
color: navy;
margin-bottom: 20px;
}
Minified CSS:
/* Minified CSS */
body{margin:0;padding:0;font-family:Arial,sans-serif;}h1{color:navy;margin-bottom:20px;}
Minified CSS reduces the file size by eliminating unnecessary characters, which can improve the loading time of your website.
Best Practices
- Use Proper Indentation and Line Breaks: Even though the browser doesn’t care about white space, using indentation and line breaks makes your code more readable and easier to maintain.
- Always End with a Semicolon: To avoid any issues with browser interpretation, always include a semicolon after each property-value pair.
- Minify for Production: When your CSS is ready for deployment, consider minifying it to reduce file size and improve performance.
By following these syntax rules and best practices, you ensure that your CSS is both effective in styling your web pages and efficient in terms of performance.
Attached to HTML
To apply CSS to a webpage, it needs to be loaded and defined within the HTML document that it will affect. This can be done in several ways, each with its own use cases and advantages:
1. Externally
External CSS involves linking a separate .css file to your HTML document. This method is ideal for larger websites where you want to keep your styling separate from your content, allowing for cleaner code and easier maintenance.
Example:
In your HTML file, you would link to an external CSS file like this:
<!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="styles.css">
<title>My Website</title>
</head>
<body>
<h1>Welcome to My Website</h1>
</body>
</html>
In this case, styles.css is the external file where all your CSS rules are defined. This method keeps your HTML clean and separates the content from the styling.
2. In the <head>
CSS can also be included directly within the <head> section of your HTML document using the <style> tag. This method is useful when you want to apply styles specific to a single page or when you have a small amount of CSS that doesn’t justify a separate file.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
h1 {
color: navy;
text-align: center;
}
</style>
<title>My Website</title>
</head>
<body>
<h1>Welcome to My Website</h1>
</body>
</html>
Here, the CSS is directly embedded in the <head>, which is quick and effective for small projects or specific pages.
3. Inline
Inline CSS involves applying styles directly to HTML elements using the style attribute. This method is best for applying styles to individual elements when you don’t need to reuse the styles elsewhere or when you want to override other CSS rules for a specific element.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Website</title>
</head>
<body>
<h1 style="color: navy; text-align: center;">Welcome to My Website</h1>
<p style="font-size: 20px; color: gray;">This is a paragraph with inline styling.</p>
</body>
</html>
In this example, the h1 and p elements have their styles defined directly in the HTML using the style attribute. This method is handy for quick changes or specific styling needs but can make the HTML harder to maintain if overused.
When to Use Each Method
-
External CSS: Best for larger projects or when you want to keep your styles organized and separate from your HTML content. It promotes reusability and easier maintenance.
-
In the
<head>: Ideal for single-page styling or when you have a small amount of CSS that doesn’t require an external file. It’s also useful for testing and prototyping. -
Inline CSS: Useful for applying styles to specific elements without affecting the rest of the page or for overriding other styles. However, it should be used sparingly to avoid cluttering the HTML and making it difficult to manage.
Each method has its own advantages and ideal use cases, and understanding when to use each one will help you write more efficient, maintainable, and organized code.
W3C
CSS, originally created by Håkon Wium Lie and Tim Berners-Lee, was standardized in 1994 (28 years ago) by the W3C.
From version 3, CSS has been split and released in modules - see W3C CSS Current Work. It’s important to note the different levels at W3C:
| Level | Description |
|---|---|
| WD | Working Draft |
| CR | Candidate Recommendation |
| PR | Proposed Recommendation |
| REC | Recommendation |
Many of the mentioned modules are not REC, which means they may not necessarily work in all browsers. A good site for assurance is Can I Use, but the best method is naturally testing, possibly through BrowserStack.
W3C also oversees the standardization of many other web related technologies. Moreover, W3C provides various tools, particularly for validating HTML and CSS.
CSS Selectors
A CSS selector is a search string used by the browser to find the elements that should be affected by CSS.
For example, it could target all p tags:
All h1 tags under a section:
All elements with the class red:
The element with button1 as an ID:
There are a myriad of other selectors, some of which can be quite advanced.
CSS Properties
Once elements are identified with a CSS selector, they can be influenced by a wide range of properties related to, for example:
- Colors
- Patterns
- Fonts
- Sizes
- Placements
- Borders
- Animations
- Dynamic properties related to the client/size
- And much more
Examples of CSS
Here are a few small examples, but there are many properties available.
Texts
This example demonstrates how to style paragraphs (p tags) with various CSS properties, such as font size, color, background color, font style, and width.
CSS Cascade
The CSS Cascade is a fundamental concept in web development, controlling how styles are applied when multiple CSS rules conflict. It operates based on three key principles: source order, specificity, and importance. Understanding these principles is essential for developers to create consistent and predictable designs.
-
Source Order: When multiple CSS rules target the same element with the same specificity and importance, the rule that appears last in the stylesheet takes precedence.
-
Specificity: Specificity is calculated based on the types of selectors used. A more specific selector (e.g., an ID selector) will override a less specific one (e.g., a class or type selector). Specificity is determined by a simple point system: inline styles are the most specific, followed by IDs, classes, attributes, and pseudo-classes, and finally, element selectors.
-
Importance: The
!importantdeclaration gives a rule the highest priority, overriding other rules regardless of their specificity or order. However, using!importantshould be approached cautiously, as it can make debugging and maintaining the CSS more challenging.
User Agent Stylesheet, Author Styles, and User Styles
CSS is applied from different sources: the user agent (browser), the author (web developer), and the user.
-
User Agent Stylesheet: This is the default styling provided by the browser. For example, browsers typically set default margins for the body element and style form elements like buttons and inputs in a consistent way. These styles are the lowest in the cascade hierarchy and are often overridden by styles provided by the author.
-
Author Styles: These are the CSS rules written by the developer in the stylesheet linked to the webpage. Author styles usually override user agent styles unless otherwise specified.
-
User Styles: Users can set custom styles via browser settings or extensions, which can override both author and user agent styles. These styles are applied based on the user’s preferences, such as increasing text size for better readability.
In practice, the cascade prioritizes user styles over author styles, and author styles over user agent styles, unless !important is used to alter this order. This system ensures that users can have the final say in how content is displayed, which is especially important for accessibility.
CSS Frameworks
In modern websites, many developers choose to utilize open-source CSS frameworks to efficiently establish a starting point for designing buttons, lists, grids, sections, and much more.
The most popular frameworks include:
However, there are many more, and choosing one can be somewhat subjective.
You can try experimenting with Semantic UI using the following HTML/CSS as a starting point, and refer to their documentation for buttons and the Rating module:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ... -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css"
/>
<!-- ... -->
</head>
<body>
<!-- ... -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>
<!-- ... -->
</body>
</html>
Utility-first CSS Framework
Recently, utility-first CSS frameworks, such as TailWind, have become popular. These frameworks are more raw and require a bit more knowledge, but offer greater flexibility and are not as tightly bound to a specific design. In TailWind, for example, you work with predefined classes that directly match CSS properties.
Here’s a brief example:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ... -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.0.2/tailwind.min.css" />
</head>
<body>
<!-- ... -->
</body>
</html>
Typically, TailWind is not used from a CDN but through a Node.js development process. For more information, you might find this video series on TailWind helpful.
Try It Yourself
If you want to experiment with CSS, you can use some of the many online “playgrounds” such as:
For local development, a text editor is required. Most developers use Visual Studio Code, which is free and works on all platforms. For more information, see the separate module about Visual Studio Code and its associated extensions.
These platforms provide an excellent opportunity for practicing and experimenting with CSS, offering a convenient and flexible environment for learning and testing web design concepts.
Tasks
The following tasks are available:
- Start on CSS - A simple CSS task.
- CSS Framework - Experiment with Semantic UI.
These tasks provide practical exercises to apply your CSS skills, ranging from basic styling to utilizing a CSS framework like Semantic UI. They are excellent resources for gaining hands-on experience in web styling and design.
CSS preprocessors like SASS and LESS offer a more programmatically oriented way of writing CSS. They introduce features like variables and calculations, which can be helpful in large CSS frameworks. These preprocessors translate their syntax into standard CSS.
For example, here’s a snippet of LESS code:
When transpiled, it generates the following CSS:
While preprocessors like LESS and SASS have been popular, the need for them has diminished as CSS in the W3C standard has become more mature and powerful. Many of the features offered by preprocessors are now available directly in CSS.
On the other hand, postprocessors are tools used in the distribution phase of web development. They perform tasks like:
- Checking CSS against W3C standards.
- Minifying CSS (removing unnecessary spaces and line breaks).
- Transpiling new CSS features into older CSS for broader browser support.
Examples of postprocessors include PostCSS and CSSNext.
The choice of whether to use preprocessors or postprocessors depends on your specific project requirements and workflow.