Styling with CSS

This course covers the essentials of Cascading Style Sheets (CSS) for web design. Students will learn to use selectors, apply styling properties, and create basic layouts. Topics include CSS syntax, common selectors, key properties, the box model, and an introduction to flexbox and grid. The course also touches on responsive design principles. By the end, students will be able to effectively style web pages and create simple, responsive layouts.


Styling with CSS: Selectors, Properties, and Basic Layout\

Introduction to CSS

From our last lecture, we discussed how to create the structure of a website, using HTML. In this lecture, we will discuss how to style our HTML document using CSS.

Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a document written in HTML. CSS describes how elements should be rendered on screen, on paper, in speech, or on other media.

Three Ways to Style Pages

There are three main ways to apply CSS to an HTML document:

  1. Inline Styles
  2. Internal Stylesheet
  3. External Stylesheet

1. Inline Styles

Inline styles are applied directly to HTML elements using the style attribute:

<p style="color: blue; font-size: 16px;">This is a blue paragraph.</p>

While quick and easy, inline styles are generally discouraged for larger projects as they mix content with presentation and make your HTML less maintainable.

2. Internal Stylesheet

An internal stylesheet is placed within the <style> element in the <head> section of an HTML document:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Styled Page</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
        }
        h1 {
            color: navy;
        }
    </style>
</head>
<body>
    <h1>Welcome to My Styled Page</h1>
</body>
</html>

This method is useful for single-page websites but becomes inefficient for multi-page sites.

3. External Stylesheet

An external stylesheet is a separate CSS file that's linked to your HTML document. This is the most common and recommended method for applying CSS

Using External Stylesheets Effectively

External stylesheets are crucial for maintaining large websites. They allow you to separate style from content, making your projects easier to manage. Here's how to link an external CSS file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Styled Page</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Welcome to My Styled Page</h1>
</body>
</html>

And in your styles.css file:

body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
}
h1 {
    color: navy;
}

This method allows you to maintain your styles separately from your HTML content, making your code more organized and easier to maintain.

CSS Selectors and Properties

CSS uses selectors to target HTML elements and properties to define styles.

Basic Selectors

  1. Element Selector: Selects all instances of a specific element.

    <p>This is a paragraph.</p>
    

and in your CSS:

p {
   color: black;
}
  1. Class Selector: Selects elements with a specific class attribute. Class attributes are defined in the HTML element using the class attribute (.).

    <p class="highlight">This is a paragraph.</p>
    

and in your CSS:

.highlight {
   background-color: yellow;
}
  1. ID Selector: Selects a single element with a specific id attribute. ID attributes are defined in the HTML element using the id attribute (#).

    <p id="header">This is a paragraph.</p>
    

and in your CSS:

#header {
   font-size: 24px;
}

Common CSS Properties

  • color: Sets the color of text
  • background-color: Sets the background color of an element
  • font-family: Specifies the font for text
  • font-size: Sets the size of the font
  • margin: Sets the outer margins of an element
  • padding: Sets the inner padding of an element
  • border: Sets the border of an element
  • width and height: Set the dimensions of an element
  • display: Specifies how an element should be displayed

Example:

<style>
.box {
    color: white;
    background-color: blue;
    font-family: Arial, sans-serif;
    font-size: 16px;
    margin: 10px;
    padding: 20px;
    border: 1px solid black;
    width: 200px;
    height: 100px;
    display: inline-block;
}
</style>

<p>This is a paragraph.</p>

Using Google Fonts

Custom fonts can enhance the look and feel of your website. Google Fonts provides a wide range of free fonts. Here's how to include a Google Font in your CSS:

<head>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
</head>

<body>
<p>This is a paragraph.</p>
</body>

and in your external StyleSheet:

  body {
       font-family: 'Roboto', sans-serif;
   }

Colors in CSS

CSS supports several color formats:

  1. Keyword colors: red, blue, green, etc.
  2. Hexadecimal: #FF0000 (red), #00FF00 (green), #0000FF (blue)
  3. RGB: rgb(255, 0, 0) (red), rgb(0, 255, 0) (green), rgb(0, 0, 255) (blue)
  4. RGBA: Similar to RGB but with an alpha channel for opacity: rgba(255, 0, 0, 0.5) (semi-transparent red)
  5. HSL: (red), (green), (blue)
  6. HSLA: Similar to HSL but with an alpha channel: (semi-transparent red)

Text Styling

CSS provides numerous properties for styling text:

<style>
p {
    font-family: Arial, sans-serif;
    font-size: 16px;
    font-weight: bold;
    font-style: italic;
    text-align: center;
    text-decoration: underline;
    line-height: 1.5;
    letter-spacing: 1px;
    text-transform: uppercase;
}
</style>

<p>This is a paragraph.</p>

Understanding the DOM Tree

Before we discuss different CSS positioning strategies, it's important to understand the Document Object Model (DOM). The DOM represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; this way, programming languages can interact with the page.

A web page is a document. This document can be either displayed in the browser window or as the HTML source. But it is the same document in both cases. The DOM represents that same document so it can be manipulated. The DOM is an object-oriented representation of the web page, which can be modified with a scripting language such as JavaScript.

In the DOM, every HTML element is an object and is considered a node in the DOM tree. Parent elements contain child elements, forming a tree structure. Elements that are at the same level (i.e., siblings) share the same parent. An element that is nested inside another is called a child, and the outer element is called the parent. The term "ancestors" refers to the parents, grandparents, and so on, up to the root of the tree.

Display and Positioning

The display property determines how an element is displayed. Common values include:

  • block: The element generates a block element box
  • inline: The element generates one or more inline element boxes
  • inline-block: The element generates a block element box that will be flowed with surrounding content as if it were a single inline box
  • none: The element is completely removed from the document flow

The position property specifies the positioning method used for an element:

  • static: Default positioning. Elements with position: static are positioned according to the normal flow of the document. They are not affected by top, right, bottom, or left properties.
  • relative: Positioned relative to its normal position. This means you can move them around using the top, right, bottom, and left properties, but the space they originally occupied is preserved in the document flow.
  • absolute: Elements with position: absolute are removed from the normal document flow and positioned relative to the nearest positioned ancestor (an ancestor with a position other than static). If no such ancestor exists, it will be positioned relative to the initial containing block (usually the viewport). An ancestor is any element that encloses another element at any level above it.
  • fixed: Elements with position: fixed are removed from the normal document flow and positioned relative to the viewport (browser window). They remain fixed in place even when the page is scrolled.

Example:

<style>
.container {
    position: relative;
}

.box {
    position: absolute;
    top: 20px;
    left: 30px;
}
</style>

<div class="container">
    <div class="box">This is a box.</div>
</div>

Responsive Design: Flexbox and Grid Layouts

Flexbox

Flexbox, or the Flexible Box Layout, is a one-dimensional layout method for arranging items in rows or columns within a container. It provides a more efficient way to lay out, align, and distribute space among items in a container, even when their size is unknown or dynamic.

Flexbox makes it simple to align items vertically or horizontally using a set of alignment properties, and it's particularly useful for responsive designs because it allows the container to alter its items' width/height (and order) to best fill the available space.

Key Properties of Flexbox

  • display: flex;: This property is applied to the container to define a flex container.
  • flex-direction: Defines the direction items are placed in the container. The default is row, but it can also be column.
  • justify-content: Aligns items along the main axis (e.g., left to right, right to left, top to bottom). Common values include flex-start, flex-end, center, space-between, and space-around.
  • align-items: Aligns items along the cross axis (perpendicular to the main axis). Common values include flex-start, flex-end, center, baseline, and stretch.
  • flex-wrap: By default, items will all try to fit onto one line. You can change that and allow the items to wrap as needed with this property.
  • align-content: This aligns a flex container's lines within when there is extra space in the cross-axis, similar to how justify-content aligns individual items within the main-axis.

Example Usage

<div class="container">
    <div class="item">Item 1</div>
    <div class="item">Item 2</div>
    <div class="item">Item 3</div>
</div>
.container {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
}

.item {
    flex: 1;
    margin: 10px;
}

This setup creates a flex container where three items are evenly spaced across the main axis, centered vertically within the container, and allowed to wrap onto multiple lines if necessary.

Grid

CSS Grid Layout is a powerful two-dimensional system that allows developers to create complex layouts that are both flexible and easy to maintain. It excels at dividing a page into major regions and defining the relationship in terms of size, position, and layer.

Key Properties of CSS Grid

  • display: grid;: This property defines the container as a grid container and establishes a new grid formatting context for its contents.
  • grid-template-columns and grid-template-rows: Defines the columns and rows of the grid with a space-separated list of values. The values represent the track size, and the space between them represents the grid line.
  • grid-gap: Specifies the size of the gap between the rows and columns.
  • grid-auto-flow: Controls how the auto-placement algorithm works, specifying exactly how auto-placed items get flowed into the grid.
  • grid-area: Either specifies a name for the area, or this property can be a shorthand for grid-row-start + grid-column-start + grid-row-end + grid-column-end.

Example Usage

<div class="container">
    <div class="header">Header</div>
    <div class="sidebar">Sidebar</div>
    <div class="content">Content</div>
    <div class="footer">Footer</div>
</div>
.container {
    display: grid;
    grid-template-columns: 1fr 3fr;
    grid-template-rows: auto;
    grid-gap: 10px;
}

.header {
    grid-area: 1 / 1 / 2 / 3;
}

.sidebar {
    grid-area: 2 / 1 / 3 / 2;
}

.content {
    grid-area: 2 / 2 / 3 / 3;
}

.footer {
    grid-area: 3 / 1 / 4 / 3;
}

This layout defines a grid with two columns and three rows, placing the header across the top, the sidebar on the left, the content on the right, and the footer at the bottom.

Media Queries

Media queries are a powerful feature used to apply scoped CSS styles to specific device characteristics and parameters. They are fundamental in building responsive designs.

Key Concepts

  • @media: The at-rule used to define conditions for style rules.
  • min-width and max-width: These features are used to apply styles based on the viewport width.
  • orientation: Allows the styling based on the orientation of the device (landscape or portrait).

Example Usage

@media (max-width: 600px) {
    .container {
        flex-direction: column;
    }

    .item {
        padding: 20px;
    }
}

@media (orientation: landscape) {
    .container {
        flex-direction: row;
    }
}

In this example, the .container will stack its children vertically when the viewport width is 600px or less, and horizontally when the device is in landscape orientation. This allows for a responsive layout that adjusts to both the screen size and device orientation.

CSS Animations and Transitions

CSS allows you to create animations and transitions for a more dynamic user interface.

Transitions

Transitions allow you to change property values smoothly over a given duration.

.button {
    background-color: blue;
    transition: background-color 0.3s ease;
}

.button:hover {
    background-color: navy;
}

Animations

For more complex animations, you can use CSS keyframes:

@keyframes slide-in {
    from { transform: translateX(-100%); }
    to { transform: translateX(0); }
}

.animated-element {
    animation: slide-in 0.5s forwards;
}

This code defines a slide-in animation that moves an element from 100% to the left (off-screen) to its original position.

<div class="animated-element">Animated Element</div>

This code snippet defines a slide-in animation that moves an element from 100% to the left (off-screen) to its original position. The .animated-element class applies this animation over 0.5 seconds and ensures the element stays in the final state using forwards.

Introduction to Bootstrap

Bootstrap is a powerful front-end framework used to create modern websites and web apps. It's open-source and free to use. Bootstrap includes HTML, CSS, and JavaScript components, making it easy to develop responsive, mobile-first projects on the web.

Key Features of Bootstrap

  • Responsive Grid System: Bootstrap's grid system uses a series of containers, rows, and columns to layout and align content. It's built with flexbox and is fully responsive.
  • Prebuilt Components: Bootstrap comes with numerous prebuilt components such as dropdowns, navigation bars, alerts, modals, and much more, which can be easily customized and incorporated into your projects.
  • JavaScript Plugins: It includes several jQuery and JavaScript plugins that add dynamic features, such as collapsible menus, transitions, tooltips, and tabs.
  • Utility Classes: Bootstrap has a wide range of utility classes that speed up the development process by reducing the need for CSS writing.

Getting Started with Bootstrap

To start using Bootstrap, you can link to the Bootstrap CDN in your HTML document's head section:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bootstrap Example</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1>Hello, world!</h1>
        <p>This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content.</p>
        <hr>
        <button class="btn btn-primary">Learn more</button>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

This code snippet includes the Bootstrap CSS and JS files via CDN. The container class is used to wrap site contents and align them properly using the default grid system.

Example Usage of Components

Bootstrap's component library allows you to implement complex UI elements quickly:

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
      </li>
    </ul>
  </div>
</nav>

This example demonstrates a responsive navigation bar that adjusts to different screen sizes with minimal effort, showcasing Bootstrap's utility for rapid, responsive web development. Bootstrap has a wide range of components and utilities that can be used to create complex UI elements quickly, as shown in the example above. It hosts a big number of classes, each with its own purpose, making it easy to create custom designs.

Pseudo-classes

Pseudo-classes are special keywords added to selectors that specify a special state of the selected elements. For example, :hover can be used to change the style of an element when the user hovers over it. They are used to define the CSS properties that will apply when the element is in certain states or conditions.

Common Pseudo-classes

  1. :hover - Applies when the user hovers over an element with the cursor.
  2. :focus - Applies when the element has focus (clicked on or tabbed to).
  3. :active - Applies when the element is being activated (clicked on).
  4. :visited - Applies to links that the user has visited.
  5. :first-child - Targets the first child element within a parent.
  6. :last-child - Targets the last child element within a parent.
  7. :nth-child(n) - Targets the nth child element within a parent.

Example Usage

<a href="#">Link</a>
<button>Button</button>
<input type="text">

<style>
    button :hover {
        background-color: red;
    }
    button:focus {
        background-color: green;
    }
    button:active {
        background-color: blue;
    }
</style>

Conclusion

CSS is a powerful tool for styling web pages. It allows you to control the layout, colors, typography, and even animations of your HTML elements. As you become more comfortable with CSS, you'll be able to create increasingly sophisticated and responsive designs.