CSS Basics β Selectors and Box Model
After completing this topic, you will:
Understand how CSS styles HTML, and be able to select elements with selectors to change their design.
CSS is in charge of design
If HTML is the skeleton of a webpage, then CSS (Cascading Style Sheets) is the clothing. Color, size, spacing, layout β CSS is responsible for all visible design elements.
<!-- The simplest way to apply CSS within an HTML file -->
<style>
h1 {
color: navy;
font-size: 24px;
}
p {
color: #333;
line-height: 1.6;
}
</style>
<h1>This is a heading</h1>
<p>This paragraph will have styles applied to it.</p>h1 { ... } β this is a CSS rule. h1 is the selector (which element?), and the content within the curly braces is the declaration (what style?).
Types of selectors
The most important question in CSS is, "Which element should I select and style?" This is determined by the selector.
/* Tag selector β applies to the entire tag */
p { color: gray; }
/* Class selector β starts with a period (.), can be reused on multiple elements */
.highlight { background-color: yellow; }
/* ID selector β starts with a hash (#), should only be used once per page */
#main-title { font-size: 32px; }
/* Child selector β only selects elements within a specific element */
.card p { font-size: 14px; }<h1 id="main-title">Large Title</h1>
<p class="highlight">Highlighted paragraph</p>
<p>Regular paragraph</p>In practice, the class selector (.) is used most often because it allows you to reuse a single style on multiple elements.
Box Model
Browsers treat all HTML elements as boxes. This box consists of four layers, from the inside out:
ββββββββββββββββββββββββββββ margin (outer spacing) βββ
β βββββββββββββββββββββββββ border (border) ββββ β
β β ββββββββββββββββββββββ padding (inner spacing) β β
β β β β β
β β β content (actual content) β β
β β β β β
β β ββββββββββββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββββββββββββββ
ββββββββββββββββββββββββββββββββββββββββββββββββββββ.card {
width: 300px; /* content width */
padding: 16px; /* spacing between content and border */
border: 1px solid #ddd; /* border */
margin: 20px; /* spacing from other elements */
}"Why is the actual width greater than 300px when I set the width to 300px?" β This is because padding and border are added. To prevent this, use box-sizing: border-box;, which includes padding and border within the width. This is set as the default in almost all projects.
β Apply to your bio: DevBench β HTML & CSS Basics