IT237 Web Technology I

Web Technology IUnit 410 min read

CSS Selectors, Box Model & Styling Fundamentals

Unit 4 of Web Technology I covers CSS syntax, selector types (ID, class, attribute), the Box Model (content, padding, border, margin), and styling techniques with practical examples like Daraz’s product cards and Ncell’s mobile app layout.

TAKEAWAYS:

  • CSS Selectors target elements via tags, IDs, classes, or attributes (e.g., div, #header, .btn, [type="text"]).
  • Box Model defines how elements occupy space: content + padding + border + margin (use box-sizing: border-box to simplify).
  • External CSS (linked via <link>) is reusable; internal CSS (in <style>) is page-specific; inline CSS overrides both but is hard to maintain.
  • Specificity determines which style wins: !important > ID > class > tag > universal selector.
  • Pseudo-classes (e.g., :hover, :active) enable interactive states (e.g., Ncell’s button clicks).
  • Real-world tie: Daraz uses CSS Grid for product layouts; eSewa’s forms rely on padding and border-radius for user-friendly inputs.

1. CSS Basics: Syntax and Selectors

CSS (Cascading Style Sheets) controls presentation by linking to HTML. It uses selectors to target elements.

Types of Selectors

<tag> { }Tag Selector#id { }ID Selector.class { }Class Selector[type='text'] { }Attribute Selector:hover:nth-childPseudo-class/Element* { }Universal SelectorCSS Selectors
Hierarchy of CSS Selectors with examples
  • Tag Selector: Applies to all elements of a type.
    p { color: blue; } /* All paragraphs */
    
  • ID Selector (#id): Unique per page (use sparingly).
    #header { background: #333; }
    
  • Class Selector (.class): Reusable across elements.
    .btn { padding: 10px; }
    
  • Attribute Selector: Targets elements by attributes (e.g., form inputs).
    input[type="email"] { border: 1px solid gray; }
    
  • Pseudo-classes: Style elements in specific states.
    a:hover { color: red; } /* Link on hover */
    

Selector Specificity

Specificity determines which style applies when conflicts arise. Higher specificity overrides lower:

Selector Type Specificity (0-1-0-0) Example
Universal (*) 0-0-0-0 * { color: red; }
Tag 0-1-0-0 div { color: blue; }
Class (.) 0-0-1-0 .btn { color: green; }
ID (#) 0-0-0-1 #header { color: yellow; }
Inline (style="") 1-0-0-0 <p style="color: purple;">
!important Overrides all p { color: red !important; }

Example: In a Daraz product card, a class (.product) styles all cards, while an ID (#featured) highlights the top banner.

<div class="product">...</div>
<div id="featured">...</div>

2. The Box Model: How Elements Occupy Space

Every HTML element is a box with four layers:

Properties:

  • width/height: Content area only (default).
  • padding: Space inside the border (e.g., padding: 10px;).
  • border: Defined by border: 1px solid black;.
  • margin: Space outside the border (e.g., margin: 20px;).

Problem: By default, width includes only content. To include padding/border:

.box {
  box-sizing: border-box; /* width = content + padding + border */
  width: 200px;
  padding: 10px;
  border: 2px solid #000;
  margin: 15px;
}

Real-world use: Ncell’s mobile app uses box-sizing: border-box to ensure buttons fit perfectly in their containers.


3. Linking CSS to HTML

Three ways to apply CSS:

linkapplied stylesDOM treeHTML FileCSS FileBrowser Rendering
How CSS links to HTML: External stylesheet workflow
Method Code Example Use Case Pros Cons
Inline <p style="color: red;">Hello</p> Quick overrides High specificity Hard to maintain
Internal <style> p { color: red; } </style> Single-page styling No external files needed Not reusable
External <link rel="stylesheet" href="styles.css"> Large projects (e.g., Daraz) Reusable, cacheable Requires HTTP request

Example: For a bank’s loan calculator page, external CSS (styles.css) keeps styling consistent across all pages.

<head>
  <link rel="stylesheet" href="styles.css">
</head>

4. Styling Text and Layouts

Text Styling

p {
  font-family: Arial, sans-serif;
  font-size: 16px;
  line-height: 1.5; /* Space between lines */
  text-align: center;
  color: #333;
}

Example: eSewa’s transaction messages use line-height: 1.6 for readability.

Backgrounds and Colors

body {
  background-color: #f4f4f4;
  background-image: url('pattern.png');
  background-repeat: no-repeat;
}

Example: Pathao’s app uses gradients for call-to-action buttons:

.btn {
  background: linear-gradient(to right, #ff7e5f, #feb47b);
}

Borders and Shadows

.card {
  border: 2px solid #ddd;
  border-radius: 8px; /* Rounded corners */
  box-shadow: 0 4px 8px rgba(0,0,0,0.1); /* Soft shadow */
}

Example: NEPSE’s stock ticker uses box-shadow to stand out.


5. Practical Example: Styling a Daraz Product Card

HTML:

<div class="product-card">
  <img src="product.jpg" alt="Product">
  <h3>Wireless Earbuds</h3>
  <p class="price">Rs. 2,999</p>
  <button class="add-to-cart">Add to Cart</button>
</div>

CSS:

.product-card {
  box-sizing: border-box;
  width: 200px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
  margin: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.price {
  color: #e53935;
  font-weight: bold;
}

.add-to-cart {
  background: #ff9800;
  color: white;
  border: none;
  padding: 8px 12px;
  border-radius: 4px;
}

.add-to-cart:hover {
  background: #e68a00;
}

Result:

Content (Text/images)Text/imagesPadding (Space inside border)Space inside borderBorder (Edge styling)Edge stylingMargin (Space outside border)Space outside border
CSS Box Model: Layers of a Daraz Product Card (Wireless Earbuds example)

(Visualize: A card with an image, price in red, and an orange "Add to Cart" button with hover effect.)


6. Common Pitfalls and Fixes

Issue Cause Solution
Overlapping elements Missing margin/padding Use box-sizing: border-box
Styles not applying Wrong selector specificity Increase specificity or use !important (sparingly)
Broken layouts on mobile No responsive design Use @media queries
Slow loading Too many external CSS files Minify and combine CSS files

Example Fix: If a NTC website’s button doesn’t respond to :hover, check:

  1. Is the CSS file linked correctly?
  2. Is the selector specific enough? (e.g., .btn:hover vs. button:hover)

In the Real World

  1. eSewa’s Transaction Pages

    • Idea Used: Box Model + Pseudo-classes
    • How: Transaction receipts use padding: 20px for readability and :hover on buttons to improve UX.
    • Example: The "Pay Now" button changes color on hover (background: #4CAF50 → #45a049).
  2. Pathao’s Ride Booking App

    • Idea Used: CSS Grid + External CSS
    • How: The app’s layout uses CSS Grid for driver/passenger cards, while external stylesheets ensure consistency across Android/iOS.
  3. Daraz’s Product Grid

    • Idea Used: Class Selectors + box-sizing
    • How: Every product card uses .product-card with box-sizing: border-box to maintain uniform sizing despite varying content.
  4. Ncell’s Mobile App

    • Idea Used: Pseudo-classes for Interactivity
    • How: The "Top Up" button shows a ripple effect on :active via CSS animations.

Exam Tip

  1. For "How to create borders/margins/padding":
    • Always use box-sizing: border-box in your answer (it’s a TU favorite).
    • Example:
      div {
        width: 100px;
        padding: 10px;
        border: 2px solid black;
        margin: 5px;
        box-sizing: border-box; /* Total width = 100 + 2*2 + 2*5 = 114px */
      }
      
02505007501000Tag Selector1ID Selector100Class Selector10Inline Style1000
Selector Specificity Weight (1-10-10-1000 rule)
  1. For "External vs. Internal CSS":

    • Internal CSS: Use when styling is unique to one page (e.g., a bank’s loan calculator).
    • External CSS: Use for reusable styles (e.g., Daraz’s global styles).
    • Inline CSS: Avoid unless overriding a specific element (e.g., <h1 style="color: red;">).
  2. For "Class vs. ID Selectors":

    • Class: Reusable (e.g., .btn for all buttons).
    • ID: Unique (e.g., #header for the page header).
    • Exam Trap: IDs have higher specificity—use them only for one-of-a-kind elements.
  3. For "When to use pseudo-classes":

    • Always mention :hover, :active, and :focus in your answer.
    • Example: "A WhatsApp web button uses :hover to change opacity for feedback."
  4. Visuals in Exams:

    • If asked to "draw the Box Model," sketch:
      +---------------------+
      |          Margin     |
      |   +---------------+ |
      |   |    Border     | |
      |   |   +---------+ | |
      |   |   | Padding | | |
      |   |   +---------+ | |
      |   +---------------+ |
      |          Margin     |
      +---------------------+
      
    • Label each layer clearly.

Final Note: CSS is the backbone of web design. Master selectors, the Box Model, and specificity to score full marks. Always test your CSS in browsers (Chrome DevTools is your best friend!).

Based on the TU BITM syllabus for Web Technology I (IT237), unit 4.

Discussion

Loading…