An Introduction to CSS: Selectors and the Box Model

The Labqube Team

Cascading Style Sheets, better known as CSS, play an essential role on the web by adding life and style to our HTML pages. In this post, we’re going to delve deeper into two foundational elements of CSS: selectors and the Box Model.

CSS Selectors: Targeting HTML Elements with Precision

Selectors are the tools in CSS that allow us to target specific HTML elements and apply styles to them. To help you better understand how they work, here are some examples:

Tag Selector

The tag selector selects elements based on their HTML tag type. For example, p will select all paragraph (<p>) elements in your document.

1
2
3
p {
color: red;
}

In this example, all paragraphs will have red text.

Class Selector

The class selector picks elements that have a specific class assigned. For this, the period symbol (.) is used followed by the class name.

1
2
3
.large-font {
font-size: 24px;
}

This code will apply a font size of 24px to all HTML elements with the “large-font” class.

ID Selector

The ID selector targets a specific element assigned a unique ID. The hash symbol (#) is used followed by the ID name.

1
2
3
#highlight {
background-color: yellow;
}

This code will apply a yellow background to the HTML element with the ID “highlight”.

Descendant Selector

The descendant selector targets elements that are direct or indirect children of another element. A space is used to separate the selectors.

1
2
3
div p {
text-indent: 2em;
}

This code will add a text indent to all <p> elements that are descendants of a <div> element.

CSS Box Model: Structuring Web Page Elements

The Box Model in CSS is a fundamental concept that describes how each HTML element is structured and sized on a web page. Each HTML element is considered as a rectangular box that consists of four main components: the content, padding, border, and margin.

1
2
3
4
5
6
div {
width: 200px;
padding: 15px;
border: 5px solid black;
margin: 20px;
}

This will create a <div> with a content area width of 200px. The padding, border, and margin will add extra space around the content, each with their specified width.

There you have it! A basic understanding of CSS selectors and the box model. Hopefully, this has been a good introduction for you. Don’t hesitate to play around and experiment with these concepts to better learn them. The more you practice, the more comfortable you will get with these ideas. Happy coding!

  • Title: An Introduction to CSS: Selectors and the Box Model
  • Author: The Labqube Team
  • Created at: 2023-05-30 00:00:00
  • Updated at: 2023-12-07 17:57:00
  • Link: https://www.labqube.com/2023/05/30/introduction-to-css/index.html
  • License: This work is licensed under CC BY-NC-SA 4.0.