In this lesson, we will cover the basics of CSS, focusing on selectors, properties, and values. The topics we will cover include:
Table of Contents
Understanding CSS selectors
CSS selectors are used to target specific HTML elements on a page and apply styling to them. There are several types of selectors, including:
- Element selectors: Target elements by their HTML tag name (e.g.,
p
,h1
,div
) - Class selectors: Target elements by their
class
attribute value, using a period (.
) followed by the class name (e.g.,.example-class
) - ID selectors: Target elements by their
id
attribute value, using a hash (#
) followed by the ID name (e.g.,#example-id
) - Attribute selectors: Target elements based on the presence or value of a specific attribute (e.g.,
[href]
,[src^="https"]
)
Using CSS properties and values
CSS properties are used to define the appearance and layout of HTML elements. Each property has a specific value or a set of values that can be applied. For example:
p {
color: red;
font-size: 16px;
}
In this example, the color
and font-size
properties are used to style paragraph elements with a red text color and a font size of 16 pixels.
Some common CSS properties include:
color
: Sets the text colorbackground-color
: Sets the background color of an elementfont-size
: Sets the font sizefont-family
: Sets the font familywidth
andheight
: Set the width and height of an elementmargin
,padding
,border
: Control the spacing and borders around elements
Combining selectors, properties, and values in a CSS rule
A CSS rule consists of a selector, one or more property-value pairs, and a set of curly braces ({}
). Property-value pairs are separated by a colon (:
) and end with a semicolon (;
). For example:
h1 {
color: blue;
font-family: Arial, sans-serif;
}
In this example, the h1
selector targets all <h1>
elements on the page, and the property-value pairs define the text color and font family for those elements.
Actionable Work
- Create a new CSS file and practice writing some basic CSS selectors, such as element, class, ID, and attribute selectors.
- Add CSS properties and values to your selectors to style elements on a page.
- Link your CSS file to an HTML file using the
<link>
element in the<head>
section. - Experiment with different combinations of selectors, properties, and values to achieve different visual effects on your webpage.
- Preview your work in a web browser to see the effects of your CSS rules on the page’s appearance.