CSS Basics

CSS Syntax

/* Selector: targets HTML elements */
selector {
  property: value; /* Declaration */
  property: value; /* Another declaration */
}

/* Example */
body {
  font-family: Arial, sans-serif;
  background-color: #f4f4f4;
  color: #333;
  line-height: 1.6;
}

.container {
  width: 80%;
  margin: 0 auto;
  padding: 20px;
}
Note: CSS rules consist of a selector and a declaration block containing property-value pairs.

Adding CSS to HTML

<!-- External CSS (Recommended) -->
<link rel="stylesheet" href="styles.css">

<!-- Internal CSS -->
<style>
  body {
    background-color: #f0f0f0;
  }
</style>

<!-- Inline CSS -->
<p style="color: blue; font-size: 16px;">Some text</p>

/* Importing CSS within CSS */
@import url('another-stylesheet.css');
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
Note: External CSS is preferred for better maintainability and separation of concerns.

Selectors

/* Element selector */
p { color: blue; }

/* Class selector */
.text-center { text-align: center; }

/* ID selector */
#header { background-color: #333; }

/* Attribute selector */
a[target="_blank"] { color: red; }

/* Universal selector */
* { box-sizing: border-box; }

/* Grouping selectors */
h1, h2, h3 { font-family: 'Arial', sans-serif; }

/* Descendant selector */
div p { line-height: 1.5; }

/* Child selector */
ul > li { list-style-type: square; }

/* Adjacent sibling selector */
h2 + p { margin-top: 0; }

/* General sibling selector */
h2 ~ p { color: #666; }

/* Pseudo-classes */
a:hover { text-decoration: underline; }
li:nth-child(odd) { background-color: #f9f9f9; }

/* Pseudo-elements */
p::first-line { font-weight: bold; }
p::before { content: ">> "; }

Specificity & Important

/* Specificity hierarchy (from highest to lowest):
1. Inline styles
2. IDs
3. Classes, attributes, pseudo-classes
4. Elements, pseudo-elements */

/* Example of specificity */
#main .article p { /* Specificity: 1-1-1 */
  color: blue;
}

.article p { /* Specificity: 0-1-1 */
  color: red; /* This will be overridden */
}

p { /* Specificity: 0-0-1 */
  color: green; /* This will be overridden */
}

/* Using !important (use sparingly) */
.warning {
  color: red !important;
  font-weight: bold;
}

/* Even with higher specificity, !important wins */
#main .article .warning {
  color: blue; /* Will not apply due to !important above */
}

/* Calculating specificity:
Inline: 1000, ID: 100, Class: 10, Element: 1 */
Note: Avoid overusing !important as it makes debugging difficult. Instead, increase specificity naturally.

Box Model & Layout

Box Model

/* Content box (default) */
.content-box {
  box-sizing: content-box; /* width/height = content only */
  width: 300px;
  padding: 20px;
  border: 5px solid black;
  margin: 10px;
  /* Total width = 300 + 40 + 10 + 20 = 370px */
}

/* Border box (recommended) */
.border-box {
  box-sizing: border-box; /* width/height = content + padding + border */
  width: 300px;
  padding: 20px;
  border: 5px solid black;
  margin: 10px;
  /* Total width = 300 + 20 = 320px (margin not included) */
}

/* Applying border-box to all elements */
*, *::before, *::after {
  box-sizing: border-box;
}

/* Margin and Padding */
.box {
  /* Individual sides */
  margin-top: 10px;
  margin-right: 15px;
  margin-bottom: 10px;
  margin-left: 15px;

  padding-top: 5px;
  padding-right: 10px;
  padding-bottom: 5px;
  padding-left: 10px;

  /* Shorthand - 4 values: top right bottom left */
  margin: 10px 15px 10px 15px;
  padding: 5px 10px 5px 10px;

  /* Shorthand - 3 values: top right-left bottom */
  margin: 10px 15px 10px;

  /* Shorthand - 2 values: top-bottom right-left */
  margin: 10px 15px;

  /* Shorthand - 1 value: all sides */
  margin: 10px;
}
Note: Using box-sizing: border-box makes layout calculations much easier and is considered a best practice.

Display & Positioning

/* Display properties */
.block { display: block; } /* Takes full width, new line */
.inline { display: inline; } /* Flows with content, no width/height */
.inline-block { display: inline-block; } /* Flows with content, accepts width/height */
.none { display: none; } /* Removed from layout */
.flex { display: flex; } /* Flexbox layout */
.grid { display: grid; } /* Grid layout */

/* Positioning */
.static { position: static; } /* Default, normal flow */
.relative { position: relative; } /* Relative to normal position */
.absolute { position: absolute; } /* Relative to nearest positioned ancestor */
.fixed { position: fixed; } /* Relative to viewport */
.sticky { position: sticky; } /* Toggles between relative and fixed */

/* Positioning properties */
.box {
  position: relative;
  top: 20px; /* Offset from top */
  right: 30px; /* Offset from right */
  bottom: 40px; /* Offset from bottom */
  left: 50px; /* Offset from left */
  z-index: 10; /* Stacking order */
}

/* Float and Clear */
.float-left { float: left; }
.float-right { float: right; }
.float-none { float: none; }
.clearfix::after {
  content: "";
  display: table;
  clear: both;
}
Note: Understanding the different positioning values is crucial for creating complex layouts.

Typography & Colors

Typography

/* Font properties */
body {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 16px; /* Absolute size */
  font-size: 1rem; /* Relative to root */
  font-size: 100%; /* Percentage */
  font-weight: normal; /* normal | bold | 100-900 */
  font-style: normal; /* normal | italic | oblique */
  line-height: 1.5; /* Unitless is best for accessibility */
  text-align: left; /* left | right | center | justify */
  text-decoration: none; /* none | underline | overline | line-through */
  text-transform: none; /* none | capitalize | uppercase | lowercase */
  letter-spacing: normal; /* Normal | length value */
  word-spacing: normal; /* Normal | length value */
}

/* Text overflow */
.truncate {
  white-space: nowrap; /* Prevent wrapping */
  overflow: hidden; /* Hide overflow */
  text-overflow: ellipsis; /* Add ... */
}

/* Web fonts */
@font-face {
  font-family: 'MyFont';
  src: url('myfont.woff2') format('woff2'),
       url('myfont.woff') format('woff');
  font-weight: 400;
  font-style: normal;
}

/* Using Google Fonts */
/* Add link in HTML: <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet"> */
body {
  font-family: 'Roboto', sans-serif;
}

Colors & Backgrounds

/* Color values */
.text {
  color: red; /* Named color */
  color: #ff0000; /* Hex color */
  color: #f00; /* Short hex */
  color: rgb(255, 0, 0); /* RGB */
  color: rgba(255, 0, 0, 0.5); /* RGB with alpha */
  color: hsl(0, 100%, 50%); /* HSL */
  color: hsla(0, 100%, 50%, 0.5); /* HSL with alpha */
}

/* Background properties */
.element {
  background-color: #ffffff;
  background-image: url('image.jpg');
  background-repeat: no-repeat; /* repeat | repeat-x | repeat-y | no-repeat */
  background-position: center center; /* x-position y-position */
  background-size: cover; /* cover | contain | length | percentage */
  background-attachment: scroll; /* scroll | fixed | local */
}

/* Background shorthand */
.element {
  background: #fff url('image.jpg') no-repeat center center / cover;
}

/* Gradients */
.gradient {
  background-image: linear-gradient(to right, red, yellow);
  background-image: radial-gradient(circle, red, yellow);
  background-image: conic-gradient(red, yellow, green);
}

/* Multiple backgrounds */
.multi-bg {
  background-image: url('image1.jpg'), url('image2.png');
  background-position: left top, right bottom;
  background-repeat: no-repeat, repeat;
}
Note: HSL (Hue, Saturation, Lightness) is often easier to work with than RGB for color adjustments.

Flexbox & Grid

Flexbox

/* Flex container */
.container {
  display: flex; /* or inline-flex */
  flex-direction: row; /* row | row-reverse | column | column-reverse */
  flex-wrap: nowrap; /* nowrap | wrap | wrap-reverse */
  justify-content: flex-start; /* flex-start | flex-end | center | space-between | space-around | space-evenly */
  align-items: stretch; /* stretch | flex-start | flex-end | center | baseline */
  align-content: stretch; /* stretch | flex-start | flex-end | center | space-between | space-around */
}

/* Flex items */
.item {
  order: 0; /* Default is 0, can be positive or negative */
  flex-grow: 0; /* Ability to grow if necessary */
  flex-shrink: 1; /* Ability to shrink if necessary */
  flex-basis: auto; /* Default size before remaining space distribution */
  align-self: auto; /* auto | flex-start | flex-end | center | baseline | stretch */
}

/* Flex shorthand */
.item {
  flex: 1; /* flex-grow: 1; flex-shrink: 1; flex-basis: 0%; */
  flex: 1 1 auto; /* flex-grow, flex-shrink, flex-basis */
}

/* Example: Centering with flexbox */
.center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh; /* Full viewport height */
}
Note: Flexbox is ideal for one-dimensional layouts (either a row or a column).

CSS Grid

/* Grid container */
.container {
  display: grid; /* or inline-grid */
  grid-template-columns: 1fr 1fr 1fr; /* Fraction units */
  grid-template-rows: 100px auto 100px;
  grid-template-areas: "header header header" "main main sidebar" "footer footer footer";
  gap: 20px; /* row-gap column-gap */
  justify-items: stretch; /* start | end | center | stretch */
  align-items: stretch; /* start | end | center | stretch */
  justify-content: start; /* start | end | center | stretch | space-around | space-between | space-evenly */
  align-content: start; /* start | end | center | stretch | space-around | space-between | space-evenly */
}

/* Grid items */
.item {
  grid-column-start: 1;
  grid-column-end: 3;
  grid-row-start: 1;
  grid-row-end: 2;
  grid-area: header; /* Name from grid-template-areas */
  justify-self: stretch; /* start | end | center | stretch */
  align-self: stretch; /* start | end | center | stretch */
}

/* Shorthand properties */
.item {
  grid-column: 1 / 3; /* grid-column-start / grid-column-end */
  grid-row: 1 / 2; /* grid-row-start / grid-row-end */
  grid-area: 1 / 1 / 2 / 3; /* row-start / column-start / row-end / column-end */
}

/* Responsive grid with repeat() and minmax() */
.container {
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}
Note: CSS Grid is perfect for two-dimensional layouts (both rows and columns).

Responsive Design

Media Queries

/* Basic media query structure */
@media media-type and (media-feature) {
  /* CSS rules */
}

/* Common breakpoints */
@media (max-width: 576px) { /* Extra small devices */
  .container { padding: 10px; }
}

@media (min-width: 577px) and (max-width: 768px) { /* Small devices */
  .container { padding: 15px; }
}

@media (min-width: 769px) and (max-width: 992px) { /* Medium devices */
  .container { padding: 20px; }
}

@media (min-width: 993px) and (max-width: 1200px) { /* Large devices */
  .container { padding: 25px; }
}

@media (min-width: 1201px) { /* Extra large devices */
  .container { padding: 30px; }
}

/* Common media features */
@media (orientation: landscape) { /* Landscape mode */
  .container { max-width: 70%; }
}

@media (orientation: portrait) { /* Portrait mode */
  .container { max-width: 90%; }
}

@media (prefers-color-scheme: dark) { /* Dark mode */
  body { background: #333; color: #fff; }
}

@media (prefers-reduced-motion: reduce) { /* Reduce motion */
  * { animation: none; transition: none; }
}

/* Mobile-first approach (recommended) */
.container { /* Base styles for mobile */
  padding: 10px;
  font-size: 14px;
}

@media (min-width: 768px) { /* Tablet */
  .container {
    padding: 20px;
    font-size: 16px;
  }
}

@media (min-width: 1024px) { /* Desktop */
  .container {
    padding: 30px;
    font-size: 18px;
  }
}

Responsive Units

/* Absolute units */
.abs-units {
  width: 300px; /* Pixels */
  height: 2cm; /* Centimeters */
  font-size: 12pt; /* Points (1pt = 1/72 inch) */
}

/* Relative units */
.rel-units {
  font-size: 1rem; /* Relative to root element */
  padding: 1em; /* Relative to parent font size */
  width: 50%; /* Percentage of parent */
  height: 50vh; /* 50% of viewport height */
  width: 50vw; /* 50% of viewport width */
  margin: 2vmin; /* 1% of viewport smaller dimension */
  padding: 2vmax; /* 1% of viewport larger dimension */
}

/* Using calc() for responsive calculations */
.responsive-box {
  width: calc(100% - 40px); /* Full width minus 40px */
  height: calc(50vh + 100px); /* 50% viewport height plus 100px */
  font-size: calc(16px + 0.5vw); /* Fluid typography */
}

/* Clamp() for responsive values with limits */
.fluid-text {
  font-size: clamp(1rem, 2.5vw, 2rem); /* Min: 1rem, Preferred: 2.5vw, Max: 2rem */
}

/* Responsive images */
img {
  max-width: 100%; /* Prevent images from overflowing */
  height: auto; /* Maintain aspect ratio */
}

/* Responsive iframes */
.video-container {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 aspect ratio */
  height: 0;
  overflow: hidden;
}

.video-container iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
Note: Using relative units like rem, em, and viewport units makes your designs more flexible and responsive.

Transforms, Transitions & Animations

Transforms & Transitions

/* 2D Transforms */
.element {
  transform: translate(50px, 100px); /* Move element */
  transform: rotate(30deg); /* Rotate element */
  transform: scale(2, 3); /* Scale element */
  transform: skew(20deg, 10deg); /* Skew element */
  transform: matrix(1, 0.3, 0, 1, 0, 0); /* Combination of all */
}

/* 3D Transforms */
.element {
  transform: rotateX(45deg);
  transform: rotateY(45deg);
  transform: rotateZ(45deg);
  transform: translate3d(50px, 50px, 50px);
  transform: perspective(500px) rotateY(45deg);
}

/* Transform origin */
.element {
  transform-origin: 50% 50%; /* Default: center */
  transform-origin: top left; /* Keyword values */
  transform-origin: 20px 50px; /* Length values */
}

/* Transitions */
.element {
  transition-property: all; /* Which properties to transition */
  transition-duration: 0.5s; /* How long transition takes */
  transition-timing-function: ease; /* Timing function */
  transition-delay: 0.2s; /* Delay before transition starts */

  /* Shorthand */
  transition: all 0.5s ease 0.2s;
  transition: transform 0.3s, opacity 0.5s; /* Multiple transitions */
}

/* Timing functions */
.element {
  transition-timing-function: ease; /* Default */
  transition-timing-function: linear;
  transition-timing-function: ease-in;
  transition-timing-function: ease-out;
  transition-timing-function: ease-in-out;
  transition-timing-function: cubic-bezier(0.42, 0, 0.58, 1); /* Custom */
  transition-timing-function: steps(4, jump-end); /* Step function */
}

Animations

/* Keyframes */
@keyframes slideIn {
  from { transform: translateX(-100%); }
  to { transform: translateX(0); }
}

@keyframes fadeIn {
  0% { opacity: 0; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

@keyframes bounce {
  0%, 20%, 53%, 80%, 100% {
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    transform: translate3d(0,0,0);
  }
  40%, 43% {
    animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
    transform: translate3d(0, -30px, 0);
  }
  70% {
    animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
    transform: translate3d(0, -15px, 0);
  }
  90% { transform: translate3d(0,-4px,0); }
}

/* Applying animations */
.animated-element {
  animation-name: slideIn; /* Name of @keyframes */
  animation-duration: 1s; /* How long animation takes */
  animation-timing-function: ease; /* Timing function */
  animation-delay: 0.5s; /* Delay before animation starts */
  animation-iteration-count: infinite; /* Number of times to play */
  animation-direction: alternate; /* normal | reverse | alternate | alternate-reverse */
  animation-fill-mode: both; /* none | forwards | backwards | both */
  animation-play-state: running; /* running | paused */

  /* Shorthand */
  animation: slideIn 1s ease 0.5s infinite alternate both;
}

/* Prefers-reduced-motion media query */
@media (prefers-reduced-motion: reduce) {
  .animated-element {
    animation: none;
  }
}
Note: Always respect user preferences with prefers-reduced-motion for accessibility.