CSS Essentials

CSS Fundamentals

Basic CSS Syntax

CSS (Cascading Style Sheets) controls the visual presentation of HTML elements:

/* Style a specific element */
h1 {
  color: #333;
  font-size: 2rem;
  margin-bottom: 1rem;
}

/* Class selector */
.card {
  background: white;
  border-radius: 8px;
  padding: 1rem;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* ID selector */
#header {
  position: sticky;
  top: 0;
  z-index: 100;
}

/* Combining selectors */
.card h2 {
  color: #2563eb;
  margin-top: 0;
}

Flexbox Layout

Flexbox is perfect for one-dimensional layouts:

/* Flexbox container */
.container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}

/* Flex items */
.item {
  flex: 1;
  padding: 1rem;
}

/* Responsive flex wrap */
.gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

.gallery-item {
  flex: 1 1 300px;
}

CSS Grid

Grid is ideal for two-dimensional layouts:

/* Grid container */
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
  padding: 1rem;
}

/* Grid areas */
.layout {
  display: grid;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  grid-template-columns: 200px 1fr;
  gap: 1rem;
}

.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }

Responsive Design

Make your website adapt to different screen sizes:

/* Mobile-first approach */
.container {
  padding: 1rem;
}

/* Tablet and up */
@media (min-width: 768px) {
  .container {
    padding: 2rem;
    max-width: 768px;
    margin: 0 auto;
  }
}

/* Desktop */
@media (min-width: 1024px) {
  .container {
    max-width: 1024px;
  }
}

Best Practices

  • Use meaningful class names
  • Follow a consistent naming convention (e.g., BEM)
  • Write mobile-first media queries
  • Minimize use of !important
  • Keep selectors simple and specific
  • Use CSS custom properties for theming
  • Organize CSS with comments and sections