CSS (Cascading Style Sheets) is a language used to describe the presentation of HTML or XML documents. It controls the layout, colors, fonts, and overall visual appearance of web pages.
- Selectors: Target HTML elements to apply styles.
- Properties & Values: Define what to style and how (e.g.,
color: red;). - Cascading & Specificity: Determines which styles are applied when multiple rules target the same element.
- Box Model: Every element is a box with
margin,border,padding, andcontent.
/* Selects all paragraphs and sets their color */
p {
color: #333;
font-size: 16px;
}
/* Class selector */
.button {
background: #42b983;
color: white;
padding: 10px 20px;
border-radius: 4px;
}- Flexbox: For 1D layouts (row or column).
- Grid: For 2D layouts (rows and columns).
- Positioning:
static,relative,absolute,fixed,sticky.
- Use media queries to adapt layouts to different screen sizes:
@media (max-width: 600px) {
body {
font-size: 14px;
}
}- Keep styles modular and reusable.
- Use classes instead of IDs for styling.
- Organize CSS with comments and logical sections.
CSS variables allow you to store values for reuse throughout your stylesheet:
:root {
--main-color: #42b983;
--padding: 1rem;
}
.button {
background: var(--main-color);
padding: var(--padding);
}- Pseudo-classes: Style elements based on their state (e.g.,
:hover,:focus,:nth-child). - Pseudo-elements: Style parts of an element (e.g.,
::before,::after).
a:hover {
color: red;
}
p::first-line {
font-weight: bold;
}Add smooth effects to your UI:
.fade {
transition: opacity 0.5s;
}
.fade:hover {
opacity: 0.5;
}
@keyframes slidein {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
.slide {
animation: slidein 1s ease-in;
}Tools like SASS and LESS add features like variables, nesting, and mixins to CSS, making it more powerful and maintainable.
- Use high-contrast colors for readability.
- Ensure focus states are visible for keyboard navigation.
- Use browser DevTools to inspect and tweak styles live.
- Use the
outlineproperty for debugging layouts:
* {
outline: 1px solid #f00;
}