CSS Crash Course for Beginners: An Educational Text
Introduction to CSS
Welcome to the CSS crash course designed for complete beginners. This chapter will guide you through the fundamentals of Cascading Style Sheets (CSS), assuming no prior knowledge. If you are already familiar with CSS basics, this material might be too introductory for you.
This chapter is a continuation of an HTML crash course (referenced in the original transcript). Therefore, it is recommended to have a basic understanding of HTML before proceeding.
HTML (HyperText Markup Language) HTML is the standard markup language for creating web pages. It provides the structure and content of a webpage, using elements to define different parts of the content.
Our focus will be on the essential CSS concepts necessary for getting started with web development. CSS encompasses a wide range of topics, from basic syntax to advanced techniques. This chapter will concentrate on the foundational knowledge required to style web pages effectively. Think of it as learning the basic chords on a guitar – once you grasp the fundamentals, you can apply them creatively to style any webpage you envision.
Web Development Web development is the process of creating and maintaining websites and web applications. It encompasses various tasks, including web design, web content development, client-side/server-side scripting, and network security configuration, among others.
It’s important to note that advanced CSS topics like Flexbox and CSS Grid will be covered in separate, dedicated chapters. This chapter will solely concentrate on CSS fundamentals.
Flexbox (Flexible Box Layout) Flexbox is a CSS layout module that provides an efficient way to arrange, align, and distribute space among items in a container, even when their size is unknown or dynamic. It is particularly useful for one-dimensional layouts.
CSS Grid (Grid Layout) CSS Grid Layout is a powerful two-dimensional layout system for CSS. It enables developers to create complex and responsive web page layouts more easily by dividing web pages into rows and columns.
This chapter is designed as a comprehensive crash course, which means it is longer than typical educational videos. It is advisable to learn at your own pace, taking breaks as needed, and most importantly, to code along with the examples provided. Hands-on coding is the most effective way to learn and solidify your understanding of CSS. By the end of this chapter, you will have a solid grasp of CSS fundamentals, enabling you to style your web pages effectively.
Setting Up Your Environment
To begin working with CSS, similar to HTML, you need two essential tools: a browser and a code editor.
-
Browser: For this chapter, Google Chrome will be used as the primary browser. However, most modern browsers will work similarly for CSS development.
Browser A web browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. Examples include Chrome, Firefox, Safari, and Edge.
-
Code Editor: Visual Studio Code (VS Code) will be used as the code editor. It is a popular and versatile editor suitable for web development. You can download VS Code from code.visualstudio.com.
Code Editor A code editor is a text editor program specifically designed for editing source code of computer programs. It often includes features like syntax highlighting, auto-completion, and debugging tools to assist programmers. Visual Studio Code (VS Code) Visual Studio Code is a free source code editor made by Microsoft for Windows, Linux and macOS. It includes support for debugging, embedded Git control, syntax highlighting, intelligent code completion, snippets, and code refactoring.
After installing VS Code, it is highly recommended to install the “Prettier - Code formatter” extension. This extension automatically formats your code, making it cleaner and more readable. To install it, open VS Code, navigate to the Extensions sidebar (usually the fifth icon down on the left), and search for “Prettier”. Click install to add it to your editor.
Prettier Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.
Once your editor is set up, create a new folder for this CSS crash course. Open VS Code, and then open this newly created folder within VS Code. Inside this folder, create a new HTML file named index.html
.
HTML File An HTML file is a file containing HyperText Markup Language code. It is the basic building block of a webpage, and is typically opened and rendered by a web browser to display a webpage.
In index.html
, type !
and press the Tab
key. This shortcut in VS Code will generate a basic HTML document structure.
HTML Document An HTML document is a file written in HTML that is displayed by a web browser. It contains the content and structure of a web page, and is the foundational file for any website.
Within the <body>
tags of your index.html
file, add an <h1>
tag with the text “CSS Crash Course”.
h1 Tag The
<h1>
to<h6>
HTML tags are heading tags.<h1>
represents the most important heading and<h6>
the least. They are used to define headings in an HTML document, structuring content hierarchically.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>CSS Crash Course</h1>
</body>
</html>
To view this in your browser, right-click on index.html
in the VS Code sidebar and select “Reveal in File Explorer” (or “Reveal in Finder” on macOS). Double-click the index.html
file to open it in your browser. You should see the text “CSS Crash Course” displayed on the page.
File Explorer File Explorer (on Windows) or Finder (on macOS) is a file manager application that is used to browse and manage files and folders on a computer. It allows users to navigate their file system, create folders, open files, and perform other file-related operations.
With this setup complete, you are now ready to start learning CSS.
What is CSS?
CSS stands for Cascading Style Sheets. It is the language used to style an HTML document, controlling how elements are displayed on the screen.
Cascading Style Sheets (CSS) CSS is a style sheet language used for describing the presentation of a document written in a markup language like HTML. CSS describes how HTML elements should be displayed on screen, paper, or in other media.
It is crucial to understand that CSS is a style sheet language, not a programming language in the traditional sense.
Style Sheet Language A style sheet language is a computer language that describes the style and presentation of a document written in a markup language. It focuses on visual aspects like colors, fonts, layouts, and responsiveness.
Programming Language A programming language is a formal language used to communicate instructions to a computer. It allows programmers to create software applications, scripts, or other sets of instructions for a computer to execute.
With CSS, you can control various aspects of a web page’s appearance, including:
-
Layout: Positioning and arrangement of elements on the page.
Layout In web design, layout refers to the arrangement of visual elements on a page. It involves structuring content using elements to create a visually appealing and user-friendly interface.
-
Spacing: Controlling the space between and around elements.
Spacing Spacing in web design refers to the visual distance between elements on a webpage. It can be adjusted using CSS properties like margin, padding, and line-height to improve readability and aesthetics.
-
Text Color: Setting the color of text.
Elements In HTML, elements are the building blocks of web pages. They are defined by tags and can contain text, attributes, and other elements. Examples include headings (
<h1>
), paragraphs (<p>
), and divs (<div>
).
Essentially, CSS works by selecting HTML elements and applying styles to those selected elements.
Styles In CSS, styles are rules that specify how HTML elements should be rendered in a browser. Styles are defined using properties and values, and can control aspects like color, font, size, and layout.
Learning CSS, from a beginner’s perspective, boils down to understanding two key questions:
- How do I select an HTML element?
- What styles can I apply to that selected element?
Answering these questions effectively means learning CSS. Let’s begin with an example.
Ways to Apply CSS
There are three primary methods to add CSS styles to an HTML document:
- Inline Styles
- Internal Style Sheet
- External Style Sheet
Inline Styles
Inline styles are CSS declarations applied directly to individual HTML elements using the style
attribute. They affect only the single element to which they are applied.
Inline Styles Inline styles are CSS styles applied directly to an HTML element using the
style
attribute. They have the highest specificity and affect only the element to which they are applied, overriding external and internal stylesheets.
To use inline styles, add the style
attribute to the desired HTML element. For example, to apply an orange color to the <h1>
tag, you would add the style
attribute as follows:
<h1 style="color: orange;">CSS Crash Course</h1>
This code snippet demonstrates a CSS declaration.
CSS Declaration A CSS declaration is a single style rule that consists of a CSS property and its corresponding value. Declarations are used within CSS rules to specify how elements should be styled.
A CSS declaration is always a pair of a property and its value, separated by a colon :
.
Property (CSS) In CSS, a property is a characteristic you can change to style an element. Examples include
color
,font-size
, andbackground-color
.
Value (CSS) In CSS, a value is assigned to a property to define the specific style. For example, in
color: blue;
,blue
is the value assigned to thecolor
property.
In our example, color
is the property, and orange
is the value.
If you save index.html
and refresh your browser, you will see the text “CSS Crash Course” displayed in orange.
While inline styles are straightforward, they are generally not recommended for best practices in CSS development.
Disadvantages of Inline Styles:
- Maintenance Difficulty: If you need to apply the same style to multiple elements or change a style, you have to modify each element individually. Imagine changing the color from orange to blue across ten different elements – you would need to edit ten separate
style
attributes. - Mixing Content and Presentation: Inline styles mix HTML content (structure) with CSS presentation (style). This makes the code harder to read, understand, and maintain. Separating content and presentation is a core principle of good web development.
Use Cases for Inline Styles:
Despite the drawbacks, inline styles have limited use cases, particularly in scenarios such as:
- Styling HTML templates for emails: Email clients often have limited CSS support, making inline styles a more reliable option.
- Content Management Systems (CMS): In some CMS platforms, you might be restricted from modifying external CSS files, making inline styles a quick workaround for content styling.
However, for most web development projects, especially for beginners, it is best to avoid inline styles and use more maintainable methods.
Internal Style Sheet
An internal style sheet is defined within the <style>
HTML element, placed inside the <head>
section of your HTML document.
Internal Style Sheet An internal style sheet is a method of embedding CSS styles directly within an HTML document. It is defined inside
<style>
tags within the<head>
section of the HTML file, and applies styles only to that specific HTML document.
To use an internal style sheet, open the index.html
file and add <style>
tags within the <head>
section:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* CSS rules will go here */
</style>
</head>
<body>
<h1>CSS Crash Course</h1>
</body>
</html>
Inside the <style>
tags, you define CSS rules.
CSS Rule A CSS rule is a set of style instructions that tell the browser how to display a particular HTML element or a group of elements. It consists of a selector and a declaration block.
A CSS rule consists of two main parts:
-
Selector: Specifies which HTML element(s) the style should be applied to.
-
Declaration Block: Contains one or more style declarations, enclosed in curly braces
{}
.Selector (CSS) A CSS selector is a pattern used to select the HTML elements you want to style. Selectors can target elements by tag name, class, ID, attributes, and more.
Declaration Block (CSS) In CSS, a declaration block is a set of CSS declarations enclosed in curly braces
{}
. It follows a selector and contains one or more property-value pairs that define the styles to be applied to the selected elements.
Each declaration within the declaration block is separated by a semicolon ;
. Each declaration itself is a property-value pair, separated by a colon :
.
To color the <h1>
text orange using an internal style sheet, you would add the following CSS rule within the <style>
tags:
<style>
h1 {
color: orange;
}
</style>
In this rule:
h1
is the selector. It targets all<h1>
elements in the document.{ color: orange; }
is the declaration block.color: orange;
is the declaration.color
is the property, andorange
is the value.
Remove the inline style from the <h1>
tag in index.html
:
<body>
<h1>CSS Crash Course</h1>
</body>
Save index.html
and refresh your browser. The “CSS Crash Course” text should still be orange, but now the style is applied through the internal style sheet.
If you add another <h1>
tag in the <body>
:
<body>
<h1>CSS Crash Course</h1>
<h1>Another h1 Element</h1>
</body>
Refresh the browser. You will see that both <h1>
elements are now orange. This is because the h1
selector in the CSS rule applies to all <h1>
tags in the HTML document.
Disadvantages of Internal Style Sheets:
Similar to inline styles, internal style sheets are also not the most recommended approach for larger websites. While better than inline styles, they still have limitations:
- Maintenance for Multi-Page Websites: If your website has multiple HTML pages and you want to apply the same styles across all of them, you would need to copy the entire
<style>
block into the<head>
of each HTML file. - Inefficiency: For websites with many pages, maintaining consistency and making site-wide style changes becomes cumbersome. You would have to edit the
<style>
section in every HTML file.
Internal style sheets are somewhat useful for single-page websites or when you are restricted from modifying external CSS files (like in some CMS scenarios), but for most modern web development, external style sheets are the preferred method.
External Style Sheet
An external style sheet is the most common and recommended way to add CSS to an HTML document. It involves creating a separate file with a .css
extension to contain your CSS rules. The HTML page then links to this external CSS file.
External Style Sheet An external style sheet is a CSS file (.css extension) that contains CSS rules. It is linked to HTML documents using the
<link>
tag in the<head>
section, allowing styles to be applied to multiple HTML pages from a single CSS file.
Steps to use an external style sheet:
-
Create a CSS File: In your
css-crash-course
folder, create a new file namedstyles.css
. The.css
extension is crucial. “styles” is a common convention for naming CSS files, but you can choose other names as well. -
Move CSS Rules: Copy the CSS rule from the
<style>
block inindex.html
and paste it intostyles.css
. Yourstyles.css
file should now look like this:h1 { color: orange; }
Remove the
<style>
block from yourindex.html
file completely, as the styles are now instyles.css
. -
Link CSS File to HTML: In the
<head>
section of yourindex.html
file, add a<link>
tag to link the HTML document to yourstyles.css
file.link Tag The
<link>
tag in HTML is used to define the relationship between the current document and an external resource. It is most commonly used to link to external stylesheets, but can also be used for favicons, preloading resources, and more.The
<link>
tag requires two essential attributes for linking CSS:-
rel="stylesheet"
: Specifies the relationship between the linked file and the HTML document. In this case, it indicates that the linked file is a stylesheet.rel Attribute The
rel
attribute in the<link>
tag specifies the relationship between the current document and the linked resource. For stylesheets, it is set tostylesheet
. -
href="styles.css"
: Specifies the path to the CSS file. Ifstyles.css
is in the same folder asindex.html
, you can simply use the filename.href Attribute The
href
attribute in the<link>
tag specifies the URL of the linked resource. For stylesheets, it points to the location of the CSS file.
Your
<head>
section inindex.html
should now look like this:<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="styles.css"> </head>
Save both
index.html
andstyles.css
files. Refresh your browser, and you should still see the “CSS Crash Course” text in orange. -
Advantages of External Style Sheets:
- Maintainability: Changes to styles are made in one central CSS file, which automatically updates the styling across all linked HTML pages. This makes website maintenance much easier.
- Consistency: Ensures consistent styling across multiple pages of a website.
- Reusability: The same CSS file can be linked to multiple HTML documents, promoting code reuse and reducing redundancy.
- Performance: Browsers can cache external CSS files, meaning that once a user loads a page with an external stylesheet, subsequent pages that use the same stylesheet can load faster.
- Separation of Concerns: Keeps HTML structure and CSS presentation separate, making code cleaner, more organized, and easier to manage for both designers and developers.
Example: Styling Multiple Pages:
To demonstrate the reusability of external style sheets, create a new HTML file named about.html
in the same folder. Copy and paste all the content from index.html
into about.html
. Change the <h1>
text in about.html
to “About CSS”.
Open about.html
in your browser. You will notice that the “About CSS” heading is also orange, even though you only wrote the CSS rule in styles.css
once and linked it to both index.html
and about.html
. If you change the color in styles.css
(e.g., from orange to blue), both index.html
and about.html
will reflect the change after refreshing them in the browser.
Conclusion on CSS Application Methods:
External style sheets are the most efficient, maintainable, and widely used method for applying CSS styles to web pages. For any project beyond the simplest single-page website, external style sheets are the recommended approach.
CSS Selectors
Now that we understand how to apply CSS, let’s delve deeper into CSS selectors. As mentioned earlier, a CSS rule starts with a selector, which determines which HTML element(s) the styles will be applied to.
CSS Selectors CSS selectors are patterns used to select the HTML elements you want to style. They are the first part of a CSS rule and can target elements based on tag name, class, ID, attributes, and relationships in the document tree.
So far, we have seen the type selector (or element selector), like h1
, which selects all <h1>
elements.
Type Selector (Element Selector) A type selector, also known as an element selector, selects all HTML elements of a specific type. For example,
p
selects all<p>
elements, anddiv
selects all<div>
elements.
However, web pages often contain many different HTML tags, and you need more precise ways to target specific elements for styling. This is where various CSS selectors come into play. We will explore some of the most fundamental and commonly used selectors.
Universal Selector
The universal selector is denoted by an asterisk *
. It selects every HTML element on the page.
Universal Selector The universal selector (
*
) is a CSS selector that matches all elements in an HTML document. It is often used to apply styles that should be globally applied or to reset default styles.
To use the universal selector, replace the h1
selector in your styles.css
file with *
:
* {
color: blue;
}
In your index.html
file, add a paragraph tag <p>
with some text:
<body>
<h1>CSS Crash Course</h1>
<p>This is a paragraph of text.</p>
</body>
Refresh your browser. You will see that both the <h1>
heading and the <p>
paragraph are now blue. The universal selector has applied the color: blue;
style to all elements on the page.
Use Cases for Universal Selector:
The universal selector is primarily used for:
-
CSS Reset: To reset or normalize default browser styles. Browsers often have default styles for elements (e.g., margins, paddings, fonts). A CSS reset uses the universal selector to set these properties to a consistent baseline, ensuring a more predictable starting point for styling.
CSS Reset A CSS reset is a set of CSS rules designed to reset the default styling of HTML elements across different browsers. It aims to reduce inconsistencies by setting common properties like margins, paddings, and font sizes to a more neutral or uniform starting point.
You can search online for “CSS reset” to find popular CSS reset stylesheets and understand more about this concept.
-
Global Styling: To apply certain styles globally across the entire webpage, although this is less common than CSS resets for the universal selector.
Generally, the universal selector should be used sparingly, mainly for CSS resets or very broad, global styles. For most styling tasks, more specific selectors are preferred.
Class Selector
The class selector is one of the most frequently used selectors in CSS. It allows you to select HTML elements based on their class
attribute.
Class Selector A class selector in CSS selects HTML elements that have a specific class attribute. It is denoted by a dot (
.
) followed by the class name.
Often, you will want to style certain elements differently, even if they are the same HTML tag type. For example, you might have two paragraph elements, but you want one to be styled as an “error” message (red text) and the other as a “success” message (green text). In such cases, you can use class selectors.
In your index.html
file, replace the existing content in the <body>
with two paragraph elements:
<body>
<p>Red text</p>
<p>Green text</p>
</body>
If you were to use the element selector p
in styles.css
, it would apply the same style to both paragraphs. To style them differently, you can use the class
attribute.
Add the class
attribute to both paragraph tags:
<body>
<p class="error">Red text</p>
<p class="success">Green text</p>
</body>
Here, we have assigned the class name “error” to the first paragraph and “success” to the second. “error” and “success” are arbitrary class names, but they should be descriptive of the style or purpose.
Class Attribute The
class
attribute in HTML is a global attribute that specifies one or more class names for an HTML element. Class names are used by CSS and JavaScript to select and manipulate elements with a common characteristic or style.
To select elements with a specific class in CSS, you use a dot .
followed by the class name.
In your styles.css
file, add the following CSS rules:
.error {
color: red;
}
.success {
color: green;
}
.error
is the class selector for elements with the class “error”..success
is the class selector for elements with the class “success”.
Refresh your browser. You should see “Red text” in red and “Green text” in green. The class selectors have applied the respective styles to the paragraphs based on their class names.
Key Points about Class Selectors:
- Class names are case-sensitive.
- Multiple classes can be assigned to a single HTML element, separated by spaces (e.g.,
<p class="error important">
). - The same class can be applied to multiple HTML elements across your website, allowing you to reuse styles efficiently.
- Class selectors are a fundamental and highly versatile way to style elements in CSS.
ID Selector
The ID selector is similar to the class selector, but it is used to select a single, unique element on the page based on its id
attribute. IDs should be unique within an HTML document.
ID Selector An ID selector in CSS selects a single HTML element that has a specific
id
attribute. It is denoted by a hash symbol or pound sign (#
) followed by the ID name.
In your index.html
file, add a new paragraph tag with an id
attribute:
<body>
<p class="error">Red text</p>
<p class="success">Green text</p>
<p id="test">ID selector text</p>
</body>
Here, we have assigned the ID “test” to the third paragraph.
ID Attribute The
id
attribute in HTML is a global attribute that defines a unique identifier for an HTML element. IDs must be unique within the HTML document and are used by CSS and JavaScript to target specific elements.
To select an element with a specific ID in CSS, you use a hash symbol #
(or pound symbol) followed by the ID name.
In your styles.css
file, add the following CSS rule:
#test {
color: maroon;
}
#test
is the ID selector for the element with the ID “test”.
Refresh your browser. You should see “ID selector text” in maroon.
Use Cases for ID Selectors:
- Targeting a Unique Element: When you need to style a very specific, unique element on a page, and you know there will only ever be one such element.
- JavaScript Interaction: IDs are often used by JavaScript to uniquely identify and manipulate specific elements on a webpage.
- Specificity in CSS: ID selectors have a higher specificity than class selectors, which can be useful in certain situations (discussed later in this chapter).
However, IDs are less commonly used for styling compared to classes. Over-reliance on IDs for styling can sometimes lead to less reusable and more rigid CSS. Classes are generally preferred for styling because they promote reusability and maintainability.
Example Use Case for ID Selector:
One situation where ID selectors might be useful is when you need to override styles applied from an external library or CSS framework to a specific element.
External Library In web development, an external library is a collection of pre-written code (often JavaScript or CSS) that provides functionalities that developers can use in their projects. Libraries save time and effort by offering ready-made solutions for common tasks.
For instance, if you are using a CSS framework that applies a certain style to all paragraph elements, and you want to make one specific paragraph have a different style, using an ID selector for that paragraph can be a quick way to override the framework’s style due to the higher specificity of ID selectors.
Advanced Selectors and Combinators
Besides the basic selectors (type, universal, class, ID), CSS offers more advanced selectors and combinators to create more sophisticated selection patterns.
Combinators (CSS) Combinators are CSS selectors that define the relationship between selectors. They are used to select elements based on their position in the document tree, such as descendants, children, siblings, and adjacent siblings.
Combinators allow you to select elements based on their relationships to other elements in the HTML document structure. For example, you can select:
- A paragraph element only if it is inside a
<div>
element. - A paragraph element only if it is immediately after another paragraph element (adjacent sibling).
Examples of CSS combinators include:
- Descendant Combinator (space): Selects elements that are descendants of another element.
- Child Combinator (
>
): Selects elements that are direct children of another element. - Adjacent Sibling Combinator (
+
): Selects elements that are immediately preceded by another element (siblings). - General Sibling Combinator (
~
): Selects elements that are siblings of another element (not necessarily immediately adjacent).
Learning about combinators and advanced selectors can significantly enhance your CSS styling capabilities and allow you to target elements with greater precision. For beginners, it’s essential to master the basic selectors (type, universal, class, ID) first. Once you have a solid understanding of these fundamentals, you can explore combinators and advanced selectors to further refine your CSS skills. Resources like Mozilla Developer Network (MDN) (often referred to as “mozilla docs”) are excellent for learning more about advanced CSS selectors and combinators.
Mozilla Developer Network (MDN) Mozilla Developer Network (MDN) is a comprehensive online resource for web developers. It provides documentation, tutorials, and guides on web technologies including HTML, CSS, JavaScript, and web APIs.
Style Declarations: Color, Background Color, and Text Styling
Once you have a grasp of CSS selectors, the next step is to learn about style declarations. These are the properties and values you use within CSS rules to actually style the selected elements. Let’s explore some commonly used properties, starting with color and text styling.
Style Declarations Style declarations are the property-value pairs within a CSS rule’s declaration block that specify how selected HTML elements should be styled. Each declaration sets the value of a specific CSS property.
Color Property
The color
property is used to set the text color of an element. CSS offers various ways to specify color values. We will focus on two common methods:
-
Hex Value: A hexadecimal color code, often referred to as a “hex value”, is a way of specifying color using hexadecimal numbers. It starts with a hash symbol
#
followed by a 6-digit hexadecimal number (0-9 and A-F).Hex Value A hex value, or hexadecimal color code, is a way to represent colors in CSS using a six-digit hexadecimal number preceded by a hash symbol (
#
). The six digits represent the red, green, and blue components of the color (RR, GG, BB).#000000
represents black (all color components are 0).#FFFFFF
represents white (all color components are at their maximum value, F=15 in hexadecimal).#FF0000
is red,#00FF00
is green, and#0000FF
is blue.
-
RGBA: RGBA stands for Red, Green, Blue, Alpha. It allows you to specify a color using red, green, and blue components, as well as an alpha (opacity) component.
RGBA (Red, Green, Blue, Alpha) RGBA is a color model in CSS that allows you to specify colors using red, green, and blue components, and an alpha value for opacity. The syntax is
rgba(red, green, blue, alpha)
, where red, green, and blue are integers from 0 to 255, and alpha is a number from 0.0 (fully transparent) to 1.0 (fully opaque).-
rgba(0, 0, 0, 1)
is black (RGB components are 0, alpha is 1, fully opaque). -
rgba(255, 255, 255, 1)
is white. -
rgba(255, 0, 0, 1)
is red,rgba(0, 255, 0, 1)
is green, andrgba(0, 0, 255, 1)
is blue. -
Opacity: The alpha value controls the opacity of the color, making it partially transparent. An alpha value of
0.5
makes the color 50% transparent, and0
makes it fully transparent.Opacity Opacity in CSS refers to the degree to which content behind an element is hidden. It is controlled by the
opacity
property, which takes a value from 0.0 (fully transparent) to 1.0 (fully opaque).For example,
rgba(0, 0, 0, 0.5)
is a semi-transparent black color.
-
Example using Hex and RGBA:
.error {
color: red; /* Using color name */
}
.success {
color: #008000; /* Using hex value for green */
}
#test {
color: rgba(128, 0, 0, 0.7); /* Using RGBA for semi-transparent maroon */
}
Background Color Property
The background-color
property sets the background color of an element. You can use the same color value formats (hex, RGBA, color names) as with the color
property.
Background Color Property The
background-color
property in CSS sets the background color of an HTML element. It can accept various color values, including color names, hex values, RGB, RGBA, HSL, and HSLA.
In your index.html
file, add two new elements: a <div>
and a <span>
, both with class attributes:
<body>
<p class="error">Red text</p>
<p class="success">Green text</p>
<p id="test">ID selector text</p>
<div class="orange-bg">Orange background</div>
<span class="yellow-bg">Yellow background</span>
</body>
In styles.css
, add rules for .orange-bg
and .yellow-bg
:
.orange-bg {
background-color: orange;
}
.yellow-bg {
background-color: yellow;
}
Refresh your browser. You will see the “Orange background” <div>
with an orange background and the “Yellow background” <span>
with a yellow background.
Notice that the <div>
takes up the full width of its container (it is a block-level element), while the <span>
only takes up the space needed for its content (it is an inline element).
Block-Level Element A block-level element in HTML starts on a new line and takes up the full width available to it. Examples include
<div>
,<p>
,<h1>
to<h6>
, and<ul>
.
Inline Element An inline element in HTML does not start on a new line and only takes up as much width as necessary to contain its content. Examples include
<span>
,<a>
,<img>
, and<strong>
.
Text Styling
CSS provides numerous properties for styling text. These properties can be broadly categorized into font styles and text layout styles.
Text Styling Text styling in CSS involves using various properties to control the appearance of text content on a webpage. This includes font styles (like family, size, weight, style) and text layout styles (like alignment, line height, spacing).
Font Styles
Font styles control aspects related to the typeface and appearance of the font itself.
1. font-family
Property: Sets the font family for the text.
Font Family Property The
font-family
property in CSS specifies the typeface or font family to be used for text in an element. It can list multiple font families as fallbacks in case the primary font is not available on the user’s system.
By default, browsers use a default font (e.g., Times New Roman on Windows Chrome). You can change this using font-family
.
Example:
.font-styles {
font-family: Verdana;
}
In index.html
, add two <h1>
elements:
<body>
...
<h1 >CSS Text</h1>
<h1 class="font-styles">CSS Text with Font Style</h1>
</body>
In styles.css
, add the .font-styles
rule:
.font-styles {
font-family: Verdana;
}
Refresh your browser. The second “CSS Text” heading will appear in the Verdana font.
Web Safe Fonts and Fallbacks:
Not every font is available on every user’s computer and browser. Therefore, it’s a good practice to use web-safe fonts and provide fallback fonts.
Web Safe Font Web safe fonts are fonts that are widely available across different operating systems and browsers. Using web safe fonts ensures that your text will be displayed consistently for most users, without relying on custom font files.
Sans-serif Sans-serif is a category of fonts that do not have extending features called “serifs” at the end of strokes. Common sans-serif fonts include Arial, Helvetica, and Verdana.
When you specify font-family
, you can list multiple font families, separated by commas. The browser will try to use the first font in the list. If it’s not available, it will try the next, and so on. The last font in the list is often a generic font family like sans-serif
or serif
, which are guaranteed to be available on almost all systems.
Example with Fallback:
.font-styles {
font-family: Verdana, Arial, sans-serif; /* Verdana, then Arial, then any sans-serif font */
}
2. font-style
Property: Sets the font style (e.g., italic, normal).
Font Style Property The
font-style
property in CSS is used to set the font style of text, such as normal, italic, or oblique. It is commonly used to apply italic styling to text.
-
font-style: italic;
makes the text italicized.Italic Italic is a font style that slants the letters to the right. It is often used for emphasis, titles of works, or foreign words.
3. font-weight
Property: Sets the boldness or weight of the font.
Font Weight Property The
font-weight
property in CSS specifies the weight or boldness of the font. Common values includenormal
,bold
,lighter
,bolder
, and numerical values from 100 to 900.
-
font-weight: bold;
makes the text bold.Bold Bold is a font weight that makes text appear thicker and darker. It is often used for headings, emphasis, or important text.
<h1>
to <h6>
headings are bold by default. You can use font-weight: normal;
to make them not bold.
4. text-decoration
Property: Adds decorations to text (e.g., underline, line-through, overline).
Text Decoration Property The
text-decoration
property in CSS is used to add or remove decorations from text, such as underlines, overlines, and line-throughs. It is commonly used to remove underlines from links or to add underlines for emphasis.
-
text-decoration: underline;
underlines the text.Underline Underline is a text decoration that draws a line beneath the text. It is often used to emphasize text or to indicate hyperlinks (though underlines are less common for hyperlinks in modern web design).
5. font-size
Property: Sets the size of the font.
Font Size Property The
font-size
property in CSS specifies the size of the font of text content. It can be defined using various units, such as pixels (px
), ems (em
), rems (rem
), and percentages (%
).
-
font-size: 50px;
sets the font size to 50 pixels. Pixels (px
) are a common unit for font sizes.Pixels (px) Pixels (px) are absolute units in CSS that represent tiny dots on a screen. They are a common unit for specifying font sizes, element dimensions, and spacing in web design.
Example combining font styles:
.font-styles {
font-family: Verdana, sans-serif;
font-style: italic;
font-weight: bold;
text-decoration: underline;
font-size: 30px;
}
Text Layout Styles
Text layout styles control how text is positioned and spaced within its containing box.
Containing Box In CSS, the containing box of an element is the box within which the element is rendered and laid out. For inline elements, the containing box is typically the line box. For block-level elements, it is the content box of its parent element.
1. text-align
Property: Controls the horizontal alignment of text within its container.
Text Align Property The
text-align
property in CSS specifies the horizontal alignment of text within an element. Common values includeleft
,right
,center
, andjustify
.
text-align: center;
centers the text horizontally.text-align: right;
aligns text to the right.text-align: left;
(default) aligns text to the left.text-align: justify;
justifies the text (spreads it out to fill the line, creating even left and right edges).
Example:
.orange-bg {
background-color: orange;
text-align: center; /* Center the text in the orange div */
}
2. line-height
Property: Sets the height of each line of text.
Line Height Property The
line-height
property in CSS specifies the height of a line box. It is commonly used to adjust the vertical spacing between lines of text to improve readability.
line-height: 2;
sets the line height to twice the normal line height (relative to the font size). You can also use pixel values (e.g.,line-height: 30px;
).
Example:
.orange-bg {
background-color: orange;
text-align: center;
line-height: 2; /* Double line height */
}
3. letter-spacing
Property: Controls the spacing between letters (characters).
Letter Spacing Property The
letter-spacing
property in CSS specifies the space between characters in text. It is used to adjust the horizontal spacing between letters, making text more or less spaced out.
letter-spacing: 4px;
adds 4 pixels of space between each letter.
4. word-spacing
Property: Controls the spacing between words.
Word Spacing Property The
word-spacing
property in CSS specifies the space between words in text. It is used to adjust the horizontal spacing between words, making text more or less spaced out at the word level.
word-spacing: 20px;
adds 20 pixels of space between each word.
Example combining text layout styles:
.font-styles {
font-family: Verdana, sans-serif;
font-style: italic;
font-weight: bold;
text-decoration: underline;
font-size: 30px;
text-align: justify;
line-height: 1.5;
letter-spacing: 2px;
word-spacing: 10px;
}
Inspecting Computed Styles:
Browsers’ developer tools are invaluable for understanding CSS. In your browser, right-click on an element (e.g., the “CSS Text with Font Style” <h1>
element) and select “Inspect” or “Inspect Element”. In the developer tools panel, you will typically find tabs like “Elements” or “Inspector” and “Styles” or “Computed”.
Inspect Element (Developer Tools) Inspect Element is a feature in web browsers’ developer tools that allows users to examine the HTML and CSS of a webpage. It provides a way to view and modify the source code and styles of elements in real-time.
Navigate to the “Computed” tab. Here, you can see the rendered font and all the computed styles applied to the selected element.
Computed Styles (Developer Tools) In web browsers’ developer tools, the Computed tab (or pane) displays the final, calculated styles applied to an HTML element. It shows the values of CSS properties after inheritance, specificity, and cascading rules have been applied.
Scroll down in the “Computed” styles to find font-related properties like “font-family”, “font-size”, “font-weight”, etc. You can see the rendered font (the actual font the browser is using to display the text).
Rendered Font The rendered font is the actual typeface that a web browser uses to display text on a webpage. It is the result of the browser’s font selection process, taking into account the
font-family
property, font availability on the user’s system, and font fallback mechanisms.
For example, if you inspect the “CSS Text with Font Style” <h1>
element, you should see that the “rendered font” is indeed Verdana (if it’s available on your system), or a fallback sans-serif font if Verdana is not available.
Styling Lists and CSS Box Model
Styling Lists
CSS provides properties to style HTML lists (<ul>
- unordered list, <ol>
- ordered list, <li>
- list item).
1. list-style-type
Property: Sets the type of bullet point (for <ul>
) or numbering (for <ol>
).
List Style Type Property The
list-style-type
property in CSS specifies the marker style for list items in ordered (<ol>
) and unordered (<ul>
) lists. Common values includedisc
,circle
,square
,decimal
,lower-alpha
,upper-roman
, andnone
.
-
list-style-type: disc;
(default for<ul>
) - solid circle bullet.Disc In the context of CSS
list-style-type
,disc
is a value that specifies a filled circle as the marker for list items in an unordered list (<ul>
). It is the default marker style for unordered lists. -
list-style-type: circle;
- hollow circle bullet.Circle In the context of CSS
list-style-type
,circle
is a value that specifies a hollow circle as the marker for list items in an unordered list (<ul>
). -
list-style-type: square;
- square bullet.Square In the context of CSS
list-style-type
,square
is a value that specifies a filled square as the marker for list items in an unordered list (<ul>
). -
list-style-type: none;
- removes bullets or numbers.
Example:
In index.html
, add an unordered list:
<body>
...
<ul>
<li>Bread</li>
<li>Milk</li>
<li>Eggs</li>
</ul>
</body>
In styles.css
, add styles for ul
and li
:
ul {
list-style-type: square; /* Square bullets */
}
Refresh your browser. The list items will now have square bullets.
2. margin
and padding
for Lists:
Lists often have default margins and paddings applied by browsers. To remove these default spacings and have more control over list layout, you can set margin
and padding
to zero for the <ul>
or <ol>
element.
Margin In the CSS box model, margin is the space outside the border of an element, used to create space between the element and its neighbors.
Padding In the CSS box model, padding is the space inside the border of an element, between the border and the content.
Example removing default list spacing:
ul {
list-style-type: none; /* Remove bullets */
margin: 0; /* Remove default margin */
padding: 0; /* Remove default padding */
}
With list-style-type: none;
, you can remove the default bullets or numbers entirely, which is common in modern web design where lists are often styled without markers.
CSS Box Model
The CSS Box Model is a fundamental concept in CSS layout. It describes how HTML elements are rendered as rectangular boxes on a webpage. Understanding the box model is crucial for controlling element sizing, spacing, and layout.
CSS Box Model The CSS box model is a conceptual model that describes how HTML elements are rendered as rectangular boxes in web browsers. Each box consists of four areas: content, padding, border, and margin, which determine the element’s size and spacing in the layout.
Every HTML element is considered a box, and this box consists of four main parts (layers), from innermost to outermost:
-
Content Box: The innermost part, which contains the actual content of the element (text, images, etc.). The size of the content box is determined by properties like
width
andheight
.Content Box The content box is the innermost part of the CSS box model, containing the actual content of an element, such as text, images, or other HTML elements. Its size is determined by the
width
andheight
properties. -
Padding Box: The space surrounding the content box, inside the border. Padding is used to create space between the content and the border. The size of the padding box is controlled by the
padding
properties.Padding Box The padding box is the area surrounding the content box, inside the border. Padding creates space between the content and the border of an element.
-
Border Box: The border itself, which surrounds the padding and content. The style, thickness, and color of the border are controlled by the
border
properties.Border Box The border box is the area surrounding the padding box, outside the content and padding. It is defined by the border of an element and can be styled using properties like
border-width
,border-style
, andborder-color
. -
Margin Box: The outermost layer, representing the space outside the border. Margin is used to create space between the element’s border and other elements around it. The size of the margin box is controlled by the
margin
properties.Margin Box The margin box is the outermost area of the CSS box model, surrounding the border box. Margin creates space between the element and its neighboring elements.
Visualizing the Box Model:
Imagine each HTML element as a box with these layers stacked around the content:
+---------------------+
| Margin Box | <-- Margin (outside the border)
+---------------------+
| Border Box | <-- Border (around padding and content)
+---------------------+
| Padding Box | <-- Padding (inside the border, around content)
+---------------------+
| Content Box | <-- Content (text, images, etc.)
+---------------------+
Example using Box Model Properties:
In index.html
, add a <div>
element with the class “box-model”:
<body>
...
<div class="box-model">CSS Box Model</div>
</body>
In styles.css
, add styles for .box-model
:
.box-model {
border: 1px solid red; /* 1px solid red border */
height: 50px; /* Content height */
width: 300px; /* Content width */
padding: 20px; /* 20px padding on all sides */
margin: 20px; /* 20px margin on all sides */
}
Refresh your browser. You will see a red-bordered box with the text “CSS Box Model”.
Let’s break down what each property does:
-
border: 1px solid red;
- Sets a 1 pixel thick, solid red border around the element.Border Property The
border
property in CSS is a shorthand property for setting all border properties at once:border-width
,border-style
, andborder-color
. It defines the style, width, and color of an element’s border. -
height: 50px;
- Sets the height of the content area to 50 pixels.Height Property The
height
property in CSS specifies the height of the content area of an element. It does not include padding, border, or margin. -
width: 300px;
- Sets the width of the content area to 300 pixels.Width Property The
width
property in CSS specifies the width of the content area of an element. It does not include padding, border, or margin. -
padding: 20px;
- Adds 20 pixels of padding on all sides (top, right, bottom, left) between the content and the border.Padding Property The
padding
property in CSS is a shorthand property used to set the padding on all four sides of an element (top, right, bottom, left) at once. It creates space between the element’s content and its border. -
margin: 20px;
- Adds 20 pixels of margin on all sides around the border, creating space between this box and other elements.Margin Property The
margin
property in CSS is a shorthand property used to set the margin on all four sides of an element (top, right, bottom, left) at once. It creates space around the element, outside of its border.
Using Developer Tools to Inspect Box Model:
Right-click on the “CSS Box Model” <div>
in your browser and select “Inspect Element”. In the developer tools, look for a tab or section related to the box model (it’s often visually represented as a diagram). When you select the <div>
element in the “Elements” panel, the box model diagram will typically highlight the different parts (content, padding, border, margin) and show their dimensions. This is an extremely useful tool for visualizing and debugging CSS layout issues.
Padding and Margin in Specific Directions:
You can control padding and margin for individual sides (top, right, bottom, left) using properties like:
padding-top
,padding-right
,padding-bottom
,padding-left
margin-top
,margin-right
,margin-bottom
,margin-left
For example, padding-left: 30px;
would only add 30 pixels of padding on the left side.
border-radius
Property:
The border-radius
property adds rounded corners to the border of an element.
Border Radius Property The
border-radius
property in CSS is used to round the corners of an element’s border. It can take one, two, three, or four values to control the radius of each corner individually or in groups.
For example, border-radius: 10px;
would make the corners of the box slightly rounded.
Cascade, Specificity, and Inheritance
Three crucial concepts in CSS that affect how styles are applied are cascade, specificity, and inheritance. Understanding these concepts is essential for mastering CSS and resolving styling conflicts.
Cascade (CSS) Cascade in CSS refers to the process by which browsers resolve style conflicts when multiple CSS rules apply to the same element. It determines which style rule takes precedence based on factors like origin, specificity, and order of appearance.
Specificity (CSS) Specificity in CSS is a set of rules that browsers use to determine which CSS rule takes precedence when multiple rules apply to the same element. Selectors with higher specificity override those with lower specificity in case of conflicts.
Inheritance (CSS) Inheritance in CSS is the mechanism by which certain CSS property values set on parent elements are passed down to their child elements. Not all CSS properties are inherited, but many text-related and font-related properties are.
Cascade: Resolving Style Conflicts
The “C” in CSS stands for “Cascading”. The cascade is the algorithm that browsers use to decide which CSS rule to apply when multiple rules could potentially style the same element.
Example of Cascading Rule:
In index.html
, add an <h2>
heading:
<body>
...
<h2>Cascade Example</h2>
</body>
In styles.css
, add two CSS rules for h2
:
h2 {
color: red;
}
h2 {
color: blue;
}
Both rules target the same element type (h2
) and set the same property (color
), but with different values.
Refresh your browser. You will see that the “Cascade Example” heading is blue, not red. This is because of the cascading rule:
Cascading Rule: When multiple CSS rules with equal specificity apply to the same element, the rule that appears last in the CSS code takes precedence.
Cascading Rule The cascading rule in CSS dictates that when multiple style rules with equal specificity apply to the same element, the rule that appears latest in the stylesheet or HTML document takes precedence. This order-based conflict resolution is a key aspect of the CSS cascade.
In this example, both h2
rules have the same specificity (element selector). Therefore, the second h2
rule (color: blue;
), being defined later in styles.css
, overrides the first rule (color: red;
).
Specificity: Selector Precedence
Specificity is a system that assigns a weight or priority to different types of CSS selectors. It determines which selector is “more specific” and thus takes precedence when multiple rules apply to the same element but have different selectors.
Specificity Hierarchy (from highest to lowest):
- Inline Styles: Styles applied directly using the
style
attribute have the highest specificity. - ID Selectors: Selectors that target elements by their
id
attribute (e.g.,#myId
). - Class Selectors, Attribute Selectors, Pseudo-classes: Selectors like class selectors (e.g.,
.myClass
), attribute selectors (e.g.,[type="text"]
), and pseudo-classes (e.g.,:hover
). - Type Selectors (Element Selectors) and Pseudo-elements: Selectors that target elements by their tag name (e.g.,
h1
,p
) and pseudo-elements (e.g.,::before
,::after
). - Universal Selector: The universal selector
*
has the lowest specificity.
Example of Specificity:
In index.html
, add an <h3>
heading:
<body>
...
<h3>Specificity Example</h3>
</body>
In styles.css
, add the following CSS rules:
h3 {
color: red; /* Element selector (lower specificity) */
}
.subheading {
color: blue; /* Class selector (higher specificity than element selector) */
}
#title {
color: orange; /* ID selector (higher specificity than class selector) */
}
Now, add classes and an ID to the <h3>
element in index.html
:
<body>
...
<h3 class="subheading" id="title" style="color: purple;">Specificity Example</h3>
</body>
We have applied styles using:
- Element selector (
h3
):color: red;
- Class selector (
.subheading
):color: blue;
- ID selector (
#title
):color: orange;
- Inline style (
style="color: purple;"
):color: purple;
Refresh your browser. The “Specificity Example” heading will be purple. Let’s analyze why:
- Inline Style (Purple): Inline styles have the highest specificity, so
style="color: purple;"
overrides all other styles. - ID Selector (Orange): If we remove the inline style from
index.html
, the heading becomes orange. ID selectors have higher specificity than class and element selectors. - Class Selector (Blue): If we also remove the ID “title” from
index.html
, the heading becomes blue. Class selectors have higher specificity than element selectors. - Element Selector (Red): If we remove the class “subheading” as well, the heading becomes red. Element selectors have the lowest specificity among these.
!important
Keyword:
There is a way to override specificity rules using the !important
keyword. When !important
is appended to a CSS property value, it makes that rule the most specific, regardless of selector specificity.
!important
Keyword The!important
keyword in CSS is used to override the normal rules of specificity and the cascade. When!important
is added to a CSS property value, it makes that rule take precedence over any other conflicting rules, regardless of selector specificity or order.
Example using !important
:
In styles.css
, modify the h3
element selector rule to include !important
:
h3 {
color: red !important; /* !important keyword */
}
.subheading {
color: blue;
}
#title {
color: orange;
}
Keep the inline style, class, and ID attributes on the <h3>
element in index.html
:
<h3 class="subheading" id="title" style="color: purple;">Specificity Example</h3>
Refresh your browser. Now, the “Specificity Example” heading is red, even though there’s an inline style (purple), a class selector (blue), and an ID selector (orange) that would normally have higher specificity. The !important
keyword on the element selector rule makes it override everything else.
Caution about !important
:
While !important
can be useful in very specific situations (e.g., overriding styles from a third-party library), it should be used sparingly and with caution. Overuse of !important
can make your CSS harder to understand, maintain, and debug, as it breaks the normal specificity rules and can lead to unexpected styling conflicts. It’s generally better to rely on proper CSS specificity and cascading principles to manage styles effectively.
Inheritance: Passing Styles Down
Inheritance is a mechanism in CSS where certain CSS property values set on parent elements are automatically inherited by their child elements.
Parent Element In HTML, a parent element is an element that contains other elements, known as child elements. For example, in
<div><p>Text</p></div>
, the<div>
is the parent element of the<p>
element.
Child Element In HTML, a child element is an element that is nested inside another element, known as the parent element. For example, in
<div><p>Text</p></div>
, the<p>
is the child element of the<div>
element.
Not all CSS properties are inherited, but many common properties, especially text-related and font-related properties, are inherited by default.
Example of Inheritance:
In index.html
, add a <div>
with the class “inheritance-example” and a <p>
inside it:
<body>
...
<div class="inheritance-example">
<p>Inheritance Text</p>
</div>
</body>
In styles.css
, add styles for .inheritance-example
:
.inheritance-example {
color: orange; /* Text color for the div */
font-family: "Segoe UI"; /* Font family for the div */
font-size: 30px; /* Font size for the div */
}
Refresh your browser. You will see that the “Inheritance Text” paragraph is also orange, uses the “Segoe UI” font, and is 30 pixels in size, even though we only set these styles on the <div>
element. The <p>
element inherits these styles from its parent <div>
.
Properties that are commonly inherited:
color
font-family
,font-size
,font-weight
,font-style
text-align
,line-height
,letter-spacing
,word-spacing
list-style-type
,list-style-position
,list-style-image
Properties that are typically NOT inherited:
- Layout-related properties (e.g.,
display
,position
,float
) - Box model properties (e.g.,
width
,height
,margin
,padding
,border
) - Background properties (e.g.,
background-color
,background-image
)
Troubleshooting CSS with Cascade, Specificity, and Inheritance:
When you encounter unexpected styling issues or styles not being applied as intended, always consider cascade, specificity, and inheritance.
- Cascade: Check the order of your CSS rules. Later rules can override earlier ones with equal specificity.
- Specificity: Analyze the selectors you are using. More specific selectors (e.g., ID selectors) will override less specific ones (e.g., element selectors).
- Inheritance: Check if styles are being inherited from parent elements. Sometimes, unexpected styles might be coming from inherited properties.
Using browser developer tools to inspect elements and examine their computed styles is invaluable for understanding how cascade, specificity, and inheritance are affecting the final rendered styles.
Styling Tables
CSS is essential for making HTML tables (<table>
) visually appealing and well-structured. Without CSS, tables often look very basic and unformatted.
Basic HTML Table Structure:
<table>
<thead>
<tr>
<th>Heading 1</th>
<th>Heading 2</th>
<th>Heading 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
<tr>
<td>Data 4</td>
<td>Data 5</td>
<td>Data 6</td>
</tr>
<tr>
<td>Data 7</td>
<td>Data 8</td>
<td>Data 9</td>
</tr>
</tbody>
</table>
-
<table>
: The root element for the table.<table>
Tag The<table>
tag in HTML defines a table. It is used to structure tabular data, consisting of rows and columns. -
<thead>
: Defines the table header.<thead>
Tag The<thead>
tag in HTML defines the header content of a table. It is used to group the header rows of a table, typically containing column headings. -
<tbody>
: Defines the table body (main data content).<tbody>
Tag The<tbody>
tag in HTML defines the body content of a table. It contains the main data rows of the table, excluding the header and footer. -
<tr>
: Table row (inside<thead>
or<tbody>
).<tr>
Tag The<tr>
tag in HTML defines a row in a table. It is used within<table>
,<thead>
,<tbody>
, and<tfoot>
elements to create rows of cells. -
<th>
: Table header cell (inside<thead>
, usually for column headings).<th>
Tag The<th>
tag in HTML defines a header cell in a table. It is typically used within the<thead>
element to create column headings. -
<td>
: Table data cell (inside<tbody>
, for regular data).<td>
Tag The<td>
tag in HTML defines a data cell in a table. It is used within<tr>
elements inside<tbody>
to contain the actual data of the table.
Basic Table Styling with CSS:
-
Borders: Add borders to table cells (
<th>
and<td>
) to visually separate them.th, td { border: 1px solid #ccc; /* 1px solid gray border */ }
-
border-collapse: collapse;
on<table>
: By default, table cell borders are separated.border-collapse: collapse;
merges adjacent cell borders into a single border, making the table look more like a grid.Border Collapse Property The
border-collapse
property in CSS specifies whether table borders should be collapsed into a single border or separated.border-collapse: collapse;
merges adjacent borders, whileborder-collapse: separate;
(default) keeps them separate.table { border-collapse: collapse; /* Merge cell borders */ }
-
width: 100%;
on<table>
: To make the table take up the full available width of its container. You can also use percentage or pixel values for width.Width Property (for Tables) For tables, the
width
property in CSS specifies the width of the entire table. It can be set to a percentage to make the table responsive or to a fixed pixel value.table { border-collapse: collapse; width: 60%; /* 60% of container width */ }
-
text-align
Property: Controls text alignment within table cells.<th>
elements are center-aligned by default, and<td>
elements are left-aligned. You can override this.Text Align Property (for Tables) For table cells (
<th>
,<td>
), thetext-align
property in CSS specifies the horizontal alignment of text within the cells. It can be set toleft
,right
, orcenter
.td { text-align: center; /* Center text in data cells */ }
-
vertical-align
Property: Controls vertical alignment within table cells (top, middle, bottom). Less commonly used thantext-align
, but can be useful in some cases.Vertical Align Property The
vertical-align
property in CSS specifies the vertical alignment of inline, inline-block, and table-cell elements. For table cells (<th>
,<td>
), it controls the vertical position of content within the cell.td { text-align: center; vertical-align: bottom; /* Align text to the bottom of cells */ }
-
padding
Property: Adds spacing within table cells, making the content less cramped and more readable.Padding Property (for Tables) For table cells (
<th>
,<td>
), thepadding
property in CSS adds space between the cell content and its border. It improves readability by giving the text some breathing room within the cells.th, td { border: 1px solid #ccc; padding: 15px; /* 15px padding in cells */ }
-
border-bottom
Property: Instead of borders on all sides of cells, you can just useborder-bottom
on<th>
and<td>
to create horizontal separators between rows.Border Bottom Property The
border-bottom
property in CSS sets the style, width, and color of the bottom border of an element. It is often used in table styling to create horizontal separators between rows.th, td { border: none; /* Remove all borders */ border-bottom: 1px solid #ccc; /* Just bottom border */ padding: 15px; }
Example of Basic Table Styling:
table {
border-collapse: collapse;
width: 60%;
}
th, td {
border-bottom: 1px solid #ccc;
padding: 15px;
text-align: left; /* Default left align for data */
}
th {
text-align: center; /* Center align for headings */
}
This CSS provides a clean and functional base for styling HTML tables. You can further enhance table styles with background colors, fonts, colors, and more advanced CSS techniques.
Layout Properties: Display and Position
CSS layout properties are crucial for controlling the overall structure and arrangement of elements on a webpage. Two fundamental layout properties are display
and position
.
Layout Properties (CSS) Layout properties in CSS are a set of properties that control the arrangement and positioning of HTML elements on a webpage. They define how elements are displayed, how they flow in the document, and how they interact with each other.
Display Property
The display
property specifies the display type of an element, which determines how the element is rendered in the document flow. Every HTML element has a default display
value.
Display Property The
display
property in CSS specifies the display type of an element, which determines how the element is rendered and how it behaves in the document flow. Common values includeblock
,inline
,inline-block
,flex
,grid
, andnone
.
Common display
Values:
-
block
: Makes the element behave as a block-level element. It starts on a new line and takes up the full width available. Examples of block-level elements by default are<div>
,<p>
,<h1>
to<h6>
.Block Value (Display Property)
display: block;
makes an element behave as a block-level element. It starts on a new line, takes up the full width of its parent container, and creates a line break after the element. -
inline
: Makes the element behave as an inline element. It does not start on a new line and only takes up as much width as necessary for its content. Examples of inline elements by default are<span>
,<a>
,<img>
.Inline Value (Display Property)
display: inline;
makes an element behave as an inline element. It does not start on a new line, only takes up the necessary width to contain its content, and does not create line breaks before or after the element. -
none
: Completely removes the element from the document flow. The element is not displayed, and it does not take up any space on the page.None Value (Display Property)
display: none;
hides an element completely from the webpage. The element is removed from the document flow and does not take up any space. It is often used to hide or show elements dynamically with JavaScript.
Example using display
Property:
In index.html
, add a <div>
and a <span>
with classes “content-1” and “content-2”:
<body>
...
<div class="content-1">Sample Content 1</div>
<span class="content-2">Sample Content 2</span>
</body>
In styles.css
, add initial styles for borders:
.content-1 {
border: 1px solid red;
}
.content-2 {
border: 1px solid blue;
}
Refresh your browser. You will see the <div>
(red border, block-level) and <span>
(blue border, inline).
Now, modify the display
property in styles.css
:
.content-1 {
border: 1px solid red;
display: inline; /* Make div behave inline */
}
.content-2 {
border: 1px solid blue;
display: block; /* Make span behave block */
}
Refresh your browser again.
- The
<div>
with class “content-1” now behaves as an inline element. It no longer takes up the full width and only wraps its content. - The
<span>
with class “content-2” now behaves as a block-level element. It takes up the full width and starts on a new line.
Using display: none;
:
Add display: none;
to the .content-2
rule:
.content-2 {
border: 1px solid blue;
display: none; /* Hide the element */
}
Refresh your browser. The “Sample Content 2” <span>
element (with the blue border) will completely disappear from the page. It’s as if it’s not even in the HTML document.
Other display
Values (Beyond Beginner Level):
CSS display
has many more values, including:
-
inline-block
: An element that is like inline (flows with text) but can have width and height set, and respects vertical padding and margins. -
flex
: Enables Flexbox Layout, a powerful one-dimensional layout system for arranging items in rows or columns.Flex (Display Property)
display: flex;
activates Flexbox layout for an element, making it a flex container. Flexbox is a powerful CSS layout module for creating one-dimensional layouts, arranging items in rows or columns, and controlling their alignment and distribution of space. -
grid
: Enables CSS Grid Layout, a powerful two-dimensional layout system for creating complex grid-based layouts.Grid (Display Property)
display: grid;
activates CSS Grid Layout for an element, making it a grid container. CSS Grid is a powerful two-dimensional layout system for creating complex, grid-based page layouts with rows and columns.
Flexbox and Grid are essential for modern web layout but are more advanced topics and will be covered in separate chapters. For beginners, understanding display: block
, display: inline
, and display: none
is a great starting point.
Position Property
The position
property specifies the positioning method used for an element, which determines how it is positioned within its containing element or the viewport.
Position Property The
position
property in CSS specifies the positioning method used for an element. It determines how the element is positioned within its containing element or the viewport. Common values includestatic
,relative
,fixed
,absolute
, andsticky
.
Common position
Values:
-
static
: (Default) Elements are positioned according to the normal document flow.top
,right
,bottom
,left
properties have no effect on elements withposition: static;
.Static Value (Position Property)
position: static;
is the default value for theposition
property. Elements withposition: static;
are positioned according to the normal document flow. Thetop
,right
,bottom
, andleft
properties have no effect on static positioned elements. -
relative
: The element is positioned relative to its normal position in the document flow. You can then usetop
,right
,bottom
,left
properties to offset the element from its normal position.Relative Value (Position Property)
position: relative;
positions an element relative to its normal position in the document flow. You can then use thetop
,right
,bottom
, andleft
properties to offset the element from its normal position without affecting the layout of surrounding elements.-
top
,right
,bottom
,left
properties: These specify offsets relative to the element’s normal position. For example,top: 50px;
moves the element 50 pixels down from its normal top position.Top, Right, Bottom, Left Properties In CSS positioning, the
top
,right
,bottom
, andleft
properties are used to define the offset of a positioned element from its normal position (forrelative
,absolute
,fixed
, andsticky
positioning). They specify the distance from the top, right, bottom, or left edge of the containing block or viewport.
-
-
fixed
: The element is positioned relative to the viewport. It stays in the same position even when the page is scrolled.top
,right
,bottom
,left
properties are used to specify its position relative to the viewport edges.Fixed Value (Position Property)
position: fixed;
positions an element relative to the viewport (the browser window). Fixed elements do not scroll with the rest of the page and remain in a fixed position on the screen, even when the page is scrolled.Viewport The viewport is the visible area of a web page in a browser window. It is the part of the web page that is currently displayed on the screen, and its size varies depending on the device and browser window size.
-
absolute
: The element is removed from the normal document flow and positioned relative to its nearest positioned ancestor (an ancestor element withposition
other thanstatic
). If no positioned ancestor exists, it’s positioned relative to the initial containing block (the<html>
element, which is the document root).top
,right
,bottom
,left
properties are used to specify its position relative to the ancestor or initial containing block.Absolute Value (Position Property)
position: absolute;
positions an element relative to its nearest positioned ancestor (an ancestor withposition: relative;
,position: absolute;
, orposition: fixed;
). If no positioned ancestor is found, it is positioned relative to the initial containing block (the<html>
element). Absolute elements are removed from the normal document flow. -
sticky
: The element is positioned based on the user’s scroll position. It behaves likeposition: relative;
until a certain scroll offset is reached, and then it “sticks” to a position likeposition: fixed;
. You typically usetop
,bottom
to define the “sticking” point.Sticky Value (Position Property)
position: sticky;
positions an element based on the user’s scroll position. It behaves likeposition: relative;
until the element reaches a specified scroll offset from the top or bottom of its containing block, at which point it becomes fixed (likeposition: fixed;
) and “sticks” to that position as the user continues to scroll.
Example using position
Property:
In index.html
, add two <div>
elements with classes “position-1” and “position-2”:
<body>
...
<div class="position-1">Position Content 1</div>
<div class="position-2">Position Content 2</div>
</body>
In styles.css
, add initial styles for borders:
.position-1 {
border: 1px solid red;
height: 100px;
width: 200px;
}
.position-2 {
border: 1px solid blue;
height: 100px;
width: 200px;
}
1. position: static;
(Default):
Add position: static;
to both rules (though it’s already the default, this is for demonstration):
.position-1 {
border: 1px solid red;
height: 100px;
width: 200px;
position: static; /* Static position (default) */
}
.position-2 {
border: 1px solid blue;
height: 100px;
width: 200px;
position: static; /* Static position (default) */
}
Refresh browser. Elements are in normal flow, one after the other.
2. position: relative;
:
Change position: static;
to position: relative;
for .position-1
and add top
and left
offsets:
.position-1 {
border: 1px solid red;
height: 100px;
width: 200px;
position: relative; /* Relative position */
top: 50px; /* Offset from top */
left: 50px; /* Offset from left */
}
.position-2 {
border: 1px solid blue;
height: 100px;
width: 200px;
position: static; /* Static position */
}
Refresh browser. “Position Content 1” is moved 50px down and 50px right from its original position. “Position Content 2” remains in its normal position. Notice that the space where “Position Content 1” was originally located is still there (empty space).
3. position: fixed;
:
Change position: relative;
to position: fixed;
for .position-2
and set bottom
and right
to 0:
.position-1 {
border: 1px solid red;
height: 100px;
width: 200px;
position: relative; /* Relative position */
top: 50px;
left: 50px;
}
.position-2 {
border: 1px solid blue;
height: 100px;
width: 200px;
position: fixed; /* Fixed position */
bottom: 0; /* Bottom edge of viewport */
right: 0; /* Right edge of viewport */
}
Refresh browser and scroll the page. “Position Content 2” is now fixed to the bottom-right corner of the viewport and stays there even when you scroll.
4. position: absolute;
:
Change position: fixed;
to position: absolute;
for .position-2
:
.position-1 {
border: 1px solid red;
height: 100px;
width: 200px;
position: relative; /* Relative position */
top: 50px;
left: 50px;
}
.position-2 {
border: 1px solid blue;
height: 100px;
width: 200px;
position: absolute; /* Absolute position */
bottom: 0;
right: 0;
}
Refresh browser. “Position Content 2” is still at the bottom-right, but now it’s positioned relative to the document or a positioned ancestor. If you scroll, it will scroll with the page content (unlike fixed
).
Absolute Positioning within a Relative Parent:
To make position: absolute;
elements positioned relative to a specific container, you need to make that container a positioned ancestor by setting its position
to relative
(or absolute
or fixed
).
In index.html
, wrap “Position Content 2” <div>
in another <div>
with class “container”:
<body>
...
<div class="position-1">Position Content 1</div>
<div class="container">
<div class="position-2">Position Content 2</div>
</div>
</body>
In styles.css
, add styles for .container
and set its position
to relative
:
.container {
position: relative; /* Make container positioned ancestor */
width: 200px;
height: 2000px; /* Tall container to show scrolling effect */
border: 1px solid black;
}
.position-1 {
border: 1px solid red;
height: 100px;
width: 200px;
position: relative;
top: 50px;
left: 50px;
}
.position-2 {
border: 1px solid blue;
height: 100px;
width: 200px;
position: absolute; /* Absolute position */
bottom: 0;
right: 0;
}
Refresh browser and scroll. “Position Content 2” is now positioned at the bottom-right corner of the .container
<div>
, not the viewport. It scrolls with the container. This is a very common pattern in web layout: absolute positioning within a relatively positioned container.
5. position: sticky;
:
Change position: absolute;
to position: sticky;
for .position-1
and remove top
and left
offsets:
.position-1 {
border: 1px solid red;
height: 100px;
width: 200px;
position: sticky; /* Sticky position */
top: 0; /* Stick to top of viewport when scrolled */
}
.position-2 {
border: 1px solid blue;
height: 100px;
width: 200px;
position: static;
}
Refresh browser and scroll. “Position Content 1” initially flows normally. But when you scroll down to a point where it would normally scroll off the top of the viewport, it “sticks” to the top (because of top: 0;
) and stays visible until you scroll past the end of its containing block. Sticky positioning is useful for elements like navigation menus or section headers that you want to remain visible while scrolling through content.
Understanding position
property values is fundamental for creating complex and dynamic layouts in CSS.
CSS Units and Math Functions
CSS Units
CSS units are used to specify sizes and lengths in CSS property values, such as font sizes, margins, widths, etc. CSS units are broadly categorized into absolute units and relative units.
CSS Units CSS units are measurement values used in CSS to specify lengths, sizes, and distances. They are used in property values like
width
,height
,font-size
,margin
, and padding. CSS units are categorized into absolute and relative units.
1. Absolute Units:
Absolute units represent fixed, physical measurements. They are generally considered to be the same size regardless of screen size or resolution.
Absolute Units (CSS) Absolute units in CSS represent fixed, physical measurements that are intended to be the same size regardless of screen size or resolution. However, in practice, their actual physical size can vary slightly depending on the device and display settings.
Common absolute units include:
-
px
(pixels): The most common absolute unit in web design. 1 pixel is typically considered 1 dot on a screen.Pixel (px) Pixel (px) is an absolute unit in CSS that represents a tiny dot on a screen. It is the most common unit for specifying sizes, lengths, and distances in web design.
-
cm
(centimeters) -
mm
(millimeters) -
in
(inches) -
pt
(points) -
pc
(picas)
However, in web development, px
(pixels) is by far the most commonly used absolute unit. Other absolute units (cm, mm, in, pt, pc) are less frequently used, mainly for print layouts.
Use cases for absolute units:
- Layouts intended for printing, where physical sizes are important.
- Precise control over element sizes in pixel-perfect designs.
2. Relative Units:
Relative units are defined relative to something else, such as:
- Font size of the parent element.
- Font size of the root element (
<html>
). - Viewport width or height.
Relative Units (CSS) Relative units in CSS are measurement values that are defined relative to another value, such as the font size of the parent element, the font size of the root element (
<html>
), or the viewport size. Relative units allow for more flexible and responsive designs that can adapt to different screen sizes and user preferences.
Using relative units is crucial for creating responsive designs that adapt well to different screen sizes and devices.
Common relative units include:
-
em
: Relative to thefont-size
of the parent element. 1em
is equal to the computed font-size of the parent element.em
Unit Theem
unit in CSS is a relative unit that is equal to the computed font-size of the parent element. For example, if the parent element hasfont-size: 16px;
, then1em
in a child element would be16px
.em
units are often used for font sizes and element dimensions to create scalable and responsive designs. -
rem
: Relative to thefont-size
of the root element (<html>
). 1rem
is equal to the computed font-size of the root element.rem
Unit Therem
unit in CSS is a relative unit that is equal to the computed font-size of the root element (<html>
). Unlikeem
units,rem
units are not affected by the font-size of the parent element, making them more predictable and easier to use for consistent scaling across a website.Root Element In HTML, the root element is the topmost element in the document tree, which is always the
<html>
element. It is the ancestor of all other elements in the document.Body Element In HTML, the
<body>
element represents the content of an HTML document. It contains all the visible content of a web page, such as text, images, links, and other HTML elements. -
vh
: Viewport height. 1vh
is equal to 1% of the viewport height.vh
Unit (Viewport Height) Thevh
unit in CSS is a relative unit that is equal to 1% of the viewport height. For example,100vh
represents 100% of the viewport height, and50vh
represents 50% of the viewport height.vh
units are useful for creating full-height sections and responsive layouts that adapt to different screen heights.Viewport Relative Height (
vh
) Viewport relative height (vh
) is a relative CSS unit that represents a percentage of the viewport’s height. For example,50vh
is equal to 50% of the viewport height. -
vw
: Viewport width. 1vw
is equal to 1% of the viewport width.vw
Unit (Viewport Width) Thevw
unit in CSS is a relative unit that is equal to 1% of the viewport width. For example,100vw
represents 100% of the viewport width, and50vw
represents 50% of the viewport width.vw
units are useful for creating full-width sections and responsive layouts that adapt to different screen widths.Viewport Relative Width (
vw
) Viewport relative width (vw
) is a relative CSS unit that represents a percentage of the viewport’s width. For example,50vw
is equal to 50% of the viewport width. -
%
(percentage): Relative to the parent element’s size.
Example using em
, rem
, vh
, vw
:
In index.html
, add <div>
elements for em
, rem
, and vh/vw
examples:
<body>
...
<div class="em-container">
EM Unit
<div class="em-child">EM Child Element</div>
</div>
<div class="rem-container">
REM Unit
</div>
</body>
In styles.css
, add styles using em
, rem
, vh
, vw
:
.em-container {
font-size: 20px; /* Parent font size */
height: 2em; /* Height relative to parent font size (40px) */
border: 1px solid green;
}
.em-child {
font-size: 1.5em; /* Font size relative to parent .em-container (30px) */
border: 1px solid purple;
}
.rem-container {
font-size: 2rem; /* Font size relative to root font size (32px, assuming root font-size is 16px) */
height: 50vh; /* Height 50% of viewport height */
border: 1px solid #333;
}
Refresh browser and inspect elements using developer tools to see the computed sizes in pixels and how em
, rem
, vh
units work.
Key points about relative units:
em
units are contextual (relative to parent font size).rem
units provide more consistent scaling across a website (relative to root font size).vh
andvw
units are useful for creating layouts that adapt to viewport dimensions.- Using relative units is essential for responsive web design.
CSS Math Functions
CSS also provides math functions that can be used as property values, allowing for dynamic calculations in CSS. Three useful math functions are:
-
calc()
: Performs calculations (addition, subtraction, multiplication, division) in CSS.calc()
Function Thecalc()
function in CSS allows you to perform calculations with CSS property values. It can be used for arithmetic operations like addition, subtraction, multiplication, and division, combining different units and values to dynamically calculate lengths, sizes, and positions.Example using
calc()
:In
styles.css
, modify theheight
of.rem-container
usingcalc()
:.rem-container { font-size: 2rem; height: calc(50vh - 100px); /* Viewport height minus 100px */ border: 1px solid #333; }
Refresh browser. The height of
.rem-container
will now be 50% of the viewport height minus 100 pixels.calc()
is useful for dynamic layouts, especially when dealing with responsive design or component sizing relative to other elements. -
max()
: Returns the largest value from a comma-separated list of values.max()
Function Themax()
function in CSS is a math function that returns the largest value from a comma-separated list of values. It can be used to set a maximum limit for a property value, choosing between multiple options based on which one is larger.Example using
max()
:In
styles.css
, modify theheight
of.rem-container
usingmax()
:.rem-container { font-size: 2rem; height: max(50vh, 600px); /* Height is either 50vh or 600px, whichever is larger */ border: 1px solid #333; }
Refresh browser. The height of
.rem-container
will now be at least 600px, and if 50% of the viewport height is greater than 600px, it will be 50vh.max()
is useful for setting minimum dimensions or values, ensuring elements are never smaller than a certain size. -
min()
: Returns the smallest value from a comma-separated list of values.min()
Function Themin()
function in CSS is a math function that returns the smallest value from a comma-separated list of values. It can be used to set a maximum limit for a property value, choosing between multiple options based on which one is smaller.Example using
min()
:In
styles.css
, modify theheight
of.rem-container
usingmin()
:.rem-container { font-size: 2rem; height: min(50vh, 600px); /* Height is either 50vh or 600px, whichever is smaller */ border: 1px solid #333; }
Refresh browser. The height of
.rem-container
will now be at most 600px, and if 50% of the viewport height is smaller than 600px, it will be 50vh.min()
is useful for setting maximum dimensions or values, ensuring elements are never larger than a certain size.
CSS math functions like calc()
, max()
, and min()
provide powerful ways to create dynamic and flexible styles that can adapt to different conditions and screen sizes.
Conclusion
Congratulations on completing this CSS crash course! You have now covered the fundamental concepts of CSS, from basic syntax to layout properties, CSS units, and math functions. This knowledge provides a solid foundation for styling web pages effectively.
To further enhance your CSS skills, continue practicing, experimenting with different properties and values, and exploring more advanced CSS topics like Flexbox and CSS Grid, which will be covered in future learning materials.
Remember to utilize browser developer tools extensively to inspect styles, understand the box model, and debug CSS issues. Consistent practice and exploration are key to mastering CSS and becoming proficient in web development.