Web Technology IUnit 413 min read
CSS Selectors, Box Model & Styling: Layouts, Flexibility & Design
Unit 4 of Web Technology I: teaches how to use CSS selectors to target HTML elements, master the box model for precise layout control, and apply styling techniques to create responsive and visually appealing web pages.
TAKEAWAYS:
- Learn CSS selectors (element, class, ID, attribute) to precisely target and style HTML elements.
- Understand the box model (content, padding, border, margin) to control spacing and layout in web pages.
- Apply flexible styling (colors, fonts, backgrounds) to enhance user experience and aesthetics.
- Use CSS inheritance and specificity to manage styling conflicts and create consistent designs.
- Explore responsive design basics using relative units (em, rem, %) and media queries.
- Combine selectors and box model to build modern, scalable web layouts.
1. Introduction to CSS Selectors
CSS (Cascading Style Sheets) is the language used to style HTML elements. Selectors determine which elements in an HTML document will be styled. Without selectors, CSS would not know which parts of the page to modify.
Types of CSS Selectors
CSS selectors allow you to target specific HTML elements for styling. Here are the most commonly used selectors:
stateDiagram-v2
[*] --> ElementSelector: Targets all elements of a type (e.g., p, div)
ElementSelector --> ClassSelector: Targets elements with a specific class (e.g., .header)
ClassSelector --> IDSelector: Targets a single element with a unique ID (e.g., #main-content)
IDSelector --> AttributeSelector: Targets elements based on attributes (e.g., [type="text"])
AttributeSelector --> PseudoClassSelector: Targets elements based on state (e.g., :hover, :active)Worked Example: Targeting Elements with Selectors
Consider the following HTML:
<div class="container">
<h1 id="main-title">Welcome to My Website</h1>
<p class="intro">This is an introductory paragraph.</p>
<button type="button" class="btn">Click Me</button>
</div>
To style these elements using CSS selectors:
/* Target all paragraphs */
p {
color: blue;
}
/* Target the element with class "intro" */
.intro {
font-size: 16px;
}
/* Target the element with ID "main-title" */
#main-title {
color: red;
font-weight: bold;
}
/* Target all buttons with class "btn" */
.btn {
background-color: green;
color: white;
padding: 10px 20px;
}
/* Target buttons when hovered */
.btn:hover {
background-color: darkgreen;
}
Comparison Table: CSS Selectors
| Selector Type | Syntax Example | Description |
|---|---|---|
| Element Selector | p { ... } |
Styles all <p> elements on the page. |
| Class Selector | .classname { ... } |
Styles elements with the specified class. |
| ID Selector | #idname { ... } |
Styles a single element with a unique ID. |
| Attribute Selector | [type="text"] { ... } |
Styles elements based on an attribute value. |
| Pseudo-class | :hover { ... } |
Styles elements based on their state (e.g., hover, focus). |
2. The CSS Box Model
The box model is a fundamental concept in CSS that describes how elements are rendered on a web page. Every HTML element is treated as a box, which consists of four parts:
+---------------------+
| Content | ← Content (width, height)
+---------------------+
| Padding | ← Padding (inner spacing)
+---------------------+
| Border | ← Border (outline)
+---------------------+
| Margin | ← Margin (outer spacing)
+---------------------+
- Content: The actual content of the element (text, images, etc.).
- Padding: The space between the content and the border (inner spacing).
- Border: The outline around the padding (can be styled with width, style, and color).
- Margin: The space outside the border (outer spacing).
Box Model Properties
| Property | Description |
|---|---|
width |
Sets the width of the content box. |
height |
Sets the height of the content box. |
padding |
Sets the padding around the content. |
border |
Sets the border around the padding. |
margin |
Sets the margin outside the border. |
box-sizing |
Controls whether width and height include padding and border (border-box). |
Worked Example: Controlling Layout with the Box Model
Consider the following HTML and CSS:
<div class="box">
<p>This is a box with content.</p>
</div>
.box {
width: 200px;
padding: 20px;
border: 2px solid black;
margin: 10px;
box-sizing: border-box; /* Ensures padding and border are included in width */
}
Result:
- The content will be 200px wide (including padding and border due to
box-sizing: border-box). - The padding adds 20px of space inside the box.
- The border is 2px solid black.
- The margin adds 10px of space outside the box.
Real-World Example: Daraz Product Page Layout
On Daraz, product cards use the box model to create consistent layouts. Each product card has:
- A content box (product image, title, price).
- Padding to separate the content from the border.
- A border to visually separate product cards.
- Margins to create spacing between cards for better readability.
3. CSS Styling Techniques
CSS allows you to style web pages using various properties. Below are some key styling techniques:
Text Styling
/* Font family */
p {
font-family: Arial, sans-serif;
}
/* Font size */
h1 {
font-size: 24px;
}
/* Text color */
a {
color: #0066cc;
}
/* Text alignment */
p {
text-align: center;
}
Background Styling
/* Background color */
body {
background-color: #f4f4f4;
}
/* Background image */
#header {
background-image: url('background.jpg');
background-repeat: no-repeat;
background-size: cover;
}
Border Styling
/* Border style */
div {
border: 2px solid #000;
border-radius: 5px; /* Rounded corners */
}
/* Border color */
button {
border-color: #4CAF50;
}
Worked Example: Styling a Navigation Bar
Consider the following HTML for a navigation bar:
<nav class="navbar">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
To style it with CSS:
.navbar {
background-color: #333;
padding: 10px 0;
}
.navbar ul {
list-style-type: none;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
}
.navbar li {
margin: 0 15px;
}
.navbar a {
color: white;
text-decoration: none;
padding: 5px 10px;
border-radius: 4px;
}
.navbar a:hover {
background-color: #555;
}
Result:
- The navigation bar has a dark background.
- Links are centered and have no underline.
- Hovering over a link changes its background color.
4. CSS Inheritance and Specificity
CSS inheritance allows properties to cascade down to child elements unless overridden. Specificity determines which CSS rule takes precedence when conflicts arise.
CSS Specificity Rules
| Selector Type | Specificity Value |
|---|---|
Universal (*) |
0 |
| Element | 1 |
| Class, Pseudo-class | 10 |
| ID | 100 |
| Inline Style | 1000 |
Worked Example: Specificity Conflict
Consider the following CSS:
/* Rule 1: Targets all paragraphs */
p {
color: blue;
}
/* Rule 2: Targets paragraphs with class "highlight" */
.highlight {
color: red;
}
/* Rule 3: Targets a specific paragraph by ID */
#special-paragraph {
color: green;
}
If the HTML is:
<p>This is a paragraph.</p>
<p class="highlight">This is a highlighted paragraph.</p>
<p id="special-paragraph">This is a special paragraph.</p>
The specificity of each rule determines the final color:
- The first
<p>will be blue (lowest specificity). - The second
<p>will be red (class selector has higher specificity than element selector). - The third
<p>will be green (ID selector has the highest specificity).
5. Responsive Design Basics
Responsive design ensures that web pages look good on all devices (desktops, tablets, and mobile phones). This is achieved using:
- Relative units (e.g.,
em,rem,%). - Media queries to apply different styles based on screen size.
Relative Units
| Unit | Description |
|---|---|
em |
Relative to the font size of the parent element. |
rem |
Relative to the root (<html>) font size. |
% |
Relative to the parent element's width or height. |
Media Queries
Media queries allow you to apply styles based on the device's characteristics (e.g., screen width).
/* Default styles */
body {
font-size: 16px;
}
/* Styles for screens smaller than 600px */
@media (max-width: 600px) {
body {
font-size: 14px;
}
.navbar {
flex-direction: column;
}
}
Real-World Example: Pathao App Layout
The Pathao app uses responsive design to ensure its interface works seamlessly on both mobile and desktop. For example:
- On mobile, the navigation menu collapses into a hamburger menu for easier use.
- On desktop, the menu remains horizontal for better readability.
- Media queries are used to adjust font sizes, button sizes, and layout spacing based on screen width.
6. Combining Selectors and Box Model for Layouts
Combining CSS selectors with the box model allows you to create flexible and scalable layouts. Below is an example of a flexbox layout, which is widely used in modern web design.
Flexbox Basics
Flexbox is a CSS layout model that allows you to easily align, distribute, and order elements within a container.
.container {
display: flex; /* Enables flexbox layout */
flex-direction: row; /* Default: horizontal */
justify-content: space-between; /* Distributes space between items */
align-items: center; /* Vertically centers items */
gap: 10px; /* Adds space between items */
}
Worked Example: Flexbox Layout for a Dashboard
Consider a dashboard with multiple cards:
<div class="dashboard">
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>
</div>
.dashboard {
display: flex;
flex-wrap: wrap; /* Allows items to wrap to the next line */
gap: 15px;
}
.card {
flex: 1 1 200px; /* Flexible width, minimum 200px */
padding: 15px;
background-color: #f0f0f0;
border-radius: 5px;
}
Result:
- The cards will distribute evenly across the dashboard.
- If the screen is too small, the cards will wrap to the next line.
- Each card has consistent padding and rounded corners.
In the Real World
CSS selectors, the box model, and styling techniques are everywhere in the digital world. Here are three concrete examples:
eSewa Website (Nepal)
- Idea Used: CSS selectors and box model for consistent card layouts.
- How: The eSewa website uses CSS selectors to style different sections (e.g.,
.payment-card,#login-form). The box model ensures that payment cards have consistent spacing and borders, improving readability and user experience.
Google Search Results Page
- Idea Used: Responsive design with media queries.
- How: Google’s search results adapt to different screen sizes using media queries. For example, on mobile, the search bar collapses into a single line, while on desktop, it spans the full width of the page.
WhatsApp Chat Interface
- Idea Used: Flexbox for dynamic layouts.
- How: WhatsApp uses flexbox to align chat bubbles dynamically. Messages are styled with the box model to ensure consistent padding and borders, while flexbox handles the flow of messages in real time.
Exam Tip
To score full marks in this unit, focus on the following:
- Understand and apply CSS selectors (element, class, ID, attribute, pseudo-class) to target specific HTML elements.
- Master the box model (content, padding, border, margin) and explain how it controls layout.
- Demonstrate styling techniques (text, background, borders) with practical examples.
- Explain CSS inheritance and specificity with clear examples of how conflicts are resolved.
- Showcase responsive design using relative units and media queries in your answers.
- Combine selectors and box model to create a simple but effective layout (e.g., flexbox or grid).
Common Pitfalls to Avoid:
- Forgetting to include
box-sizing: border-boxin your CSS, which can lead to unexpected layout issues. - Misapplying specificity rules, causing unintended style overrides.
- Not testing your CSS on different devices, which can break responsive design.
Practice Question: Write a CSS stylesheet for a simple webpage with:
- A navigation bar using flexbox.
- A hero section with a background image and centered text.
- A card layout for three products using the box model.
- A responsive design that adjusts font sizes and layout for screens smaller than 768px.
sequenceDiagram
participant User
participant Browser
participant CSS
User->>Browser: Requests webpage
Browser->>CSS: Applies selectors to HTML elements
CSS-->>Browser: Styles elements using box model and properties
Browser->>User: Renders styled webpageBased on the TU BIM syllabus for Web Technology I (IT237), unit 4.
Discussion
Loading…