Swiftorial Logo
Home
Swift Lessons
Tutorials
Career
Resources

CSS Fundamentals

1. Introduction

Cascading Style Sheets (CSS) is the language used to style and layout web pages. It allows you to control the color, font, spacing, and positioning of HTML elements.

Key features of CSS include:

  • Separation of content and presentation
  • Responsive design capabilities
  • Support for animations and transitions

2. CSS Selectors

Selectors are patterns used to select elements you want to style. Different types include:

  • Element Selector: p { }
  • Class Selector: .className { }
  • ID Selector: #idName { }
  • Attribute Selector: [type="text"] { }
  • Pseudo-class Selector: a:hover { }
Note: CSS specificity determines which styles are applied when multiple styles conflict.

3. Box Model

The CSS box model describes the rectangular boxes generated for elements in the document tree, consisting of:

  • Content: The actual content of the box, where text and images appear.
  • Padding: Space between the content and the border.
  • Border: The area surrounding the padding.
  • Margin: Space outside the border, separating the element from others.

Example of box model in CSS:


.box {
    margin: 20px;
    border: 1px solid #000;
    padding: 10px;
    width: 200px;
}
                

4. Flexbox

Flexbox is a layout model that allows you to design complex layouts in a more efficient and predictable way than traditional models.

Key properties include:

  • display: flex; on the container
  • flex-direction: defines the direction items are placed in the flex container.
  • justify-content: aligns items on the main axis.

Example of a flex container:


.container {
    display: flex;
    justify-content: space-between;
}
                

5. CSS Grid

CSS Grid Layout is a two-dimensional layout system that enables you to create complex grid-based layouts.

Key properties include:

  • display: grid; on the container
  • grid-template-columns: defines the columns of the grid.
  • grid-template-rows: defines the rows of the grid.

Example of a grid layout:


.grid-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 10px;
}
                

6. Best Practices

To write clean and maintainable CSS, consider the following best practices:

  • Use meaningful class names.
  • Organize CSS with consistent formatting.
  • Avoid inline styles.
  • Use a CSS reset to maintain consistency across browsers.
  • Utilize comments to explain complex styles.

7. FAQ

What is the difference between classes and IDs in CSS?

Classes can be used multiple times on a page, while IDs are unique to a single element.

How can I make my website responsive using CSS?

Use relative units (like percentages) and media queries to adjust styles for different screen sizes.

What are CSS preprocessors?

CSS preprocessors like SASS and LESS allow you to use variables, nested rules, and functions to write more maintainable CSS.