Welcome to the world of web design! If you already know a bit about HTML and how to use tags to structure a webpage, now is the time to bring it to life with CSS (Cascading Style Sheets). CSS is the language that transforms a basic page into something visually engaging, controlling colors, fonts, spacing, layout, and much more. With CSS, you can make your site look modern, organized, and adaptable to any screen.
In this practical guide, we will walk you through the essential concepts of CSS with clear examples you can test yourself. You do not need to be an expert: this guide is designed for beginners who want to start styling their web pages. Get ready to give your HTML a unique touch!
1. How to Link CSS to HTML
For your CSS styles to apply to an HTML page, you need to connect your CSS code with your HTML file. The most practical and recommended approach is to create a separate file with a .css extension (for example, styles.css) and link it to the HTML using the <link> tag inside the <head> section. This keeps your code clean, organized, and easy to maintain, especially in larger projects.
In this guide, all examples use an external styles.css file to demonstrate best practices right from the start.
For the examples in this guide, we have placed all the CSS in an external file called styles.css and linked it to this page to demonstrate best practices.
How does it work?
Here, you would see a centered red heading styled by the linked CSS if you test the code in your browser:
HTML:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Ejemplo Vinculación CSS</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Hola, este título tiene estilo gracias a CSS!</h1>
</body>
</html>
CSS:
h1 {
color: red; /* Cambia el color del texto a rojo */
text-align: center; /* Centra el texto */
}
2. Basic Selectors: ID and Class
How do they work?
Selectors are the way you “target” the HTML elements you want to style. The two most common selectors are ID and Class, each serving its own purpose:
- ID Selector (
#): Uses#followed by the value of theidattribute to style a unique element on the page. An ID must be unique across the entire document, serving as an exclusive identifier for a specific element. - Class Selector (
.): Uses.followed by the value of theclassattribute to apply styles to one or more elements that share that same class. It is ideal for groups of elements that you want to style similarly.
Code to try:
Here, you would see a div with bold blue text and two paragraphs with a yellow background, demonstrating how selectors target specific elements:
HTML:
<div id="principal">Este es un div con ID</div>
<p class="resaltado">Párrafo resaltado 1</p>
<p class="resaltado">Párrafo resaltado 2</p>
CSS:
#principal {
font-weight: bold; /* Texto en negrita */
color: blue; /* Color azul */
}
.resaltado {
background-color: yellow; /* Fondo amarillo */
}
3. Units of Measurement and Responsive Design
How do they work?
In CSS, measurement units define sizes, spacing, and other dimensions. There are two primary types: absolute units (such as px, which have a fixed size) and relative units (which depend on other values, such as screen size or font size).
To build websites that look great on any device (what we call responsive design), relative units are your best friends. Some of the most useful ones include:
em: Relative to the font size of the parent element.rem: Relative to the font size of the root element (<html>). More predictable thanem.%: Relative to the size of the parent container.vw: Percentage of the browser window’s total width (viewport width).100vwrepresents 100% of the viewport width.vh: Percentage of the browser window’s total height (viewport height).100vhrepresents 100% of the viewport height.
Example in action:
Here, you would see large text sized with 2rem and a box occupying 50% of the viewport width and 20% of the viewport height, adjusting automatically whenever you resize the browser window.
Code to try:
HTML:
<p class="text-rem">Texto con tamaño relativo (2rem)</p>
<div class="box-vw-vh">
Caja con tamaño relativo a la ventana (50vw x 20vh)
</div>
CSS:
.text-rem {
font-size: 2rem; /* 2 veces el tamaño de fuente raíz */
}
.box-vw-vh {
width: 50vw; /* 50% del ancho de la ventana */
height: 20vh; /* 20% del alto de la ventana */
background-color: lightblue; /* Fondo azul claro */
border-radius: 6px; /* Bordes redondeados */
text-align: center; /* Texto centrado */
line-height: 20vh; /* Centra el texto verticalmente */
box-sizing: border-box; /* Incluye padding/borde en el tamaño */
padding: 5px; /* Espacio interno */
}
4. Margin and Padding (Box Model)
How does it work?
In CSS, every HTML element behaves like a box, and the Box Model is the concept that explains how that box is structured. It consists of four parts, from the inside out:
- Content: The actual content of the element (text, images, etc.).
- Padding: The space inside the border, between the content and the border. It is used to create breathing room around inner content.
- Border: The line wrapping around the padding and content. You can configure its style, width, and color.
- Margin: The space outside the border, between this element’s border and nearby elements. It is used to separate elements from one another.
Using the margin and padding properties, you can fine-tune these spaces to keep your layout clean and well-structured.
Example in action:
Here, you would see a green box with a border, internal spacing (padding) separating text from the border, and external spacing (margin) pushing it away from adjacent elements.
Code to try:
HTML:
<div class="caja">Caja con margen y padding</div>
CSS:
.caja {
background-color: lightgreen; /* Fondo verde claro */
margin: 20px; /* 20px de espacio externo alrededor */
padding: 15px; /* 15px de espacio interno */
border: 2px solid green; /* Borde verde de 2px */
}
5. Backgrounds and Basic Styles
How does it work?
With CSS, you can make elements stand out by adding appealing backgrounds. You can use solid colors, images, or even gradients to inject personality. Background properties allow you to control how these visuals are rendered and sized, making your pages much more engaging.
Key properties include:
background-image: url('...'): Specifies the image to use.background-size: cover;: Scales the image so it covers the element’s entire surface area, clipping if necessary to avoid distortion.background-size: contain;: Scales the image to fit entirely within the element without clipping, preserving its aspect ratio. It may leave empty space.background-position: center;: Centers the background image within the element.
Example in action:
Here, you would see a box with a background image centered and scaled cleanly, creating a sleek and professional appearance.
Code to try:
HTML:
<div class="fondo"></div>
CSS:
.fondo {
width: 300px;
height: 200px;
background-image: url('https://via.placeholder.com/300x200/aaddff/000000?text=Fondo+Ejemplo');
background-size: cover; /* Cubre todo el área sin distorsionarse */
background-position: center; /* Centra la imagen */
border-radius: 6px; /* Bordes redondeados */
margin: 10px auto; /* Centra la caja horizontalmente */
border: 1px solid #ccc; /* Borde sutil */
}
6. Element Positioning
How does it work?
The position property gives you precise control over where elements sit on your page, even allowing you to take them out of the normal layout flow. This is essential for creating fixed menus, overlays, or floating elements. The main values are:
static: The default value. The element remains in the normal document flow (stacked sequentially or governed by Flexbox/Grid). Thetop,bottom,left,right, andz-indexproperties have no effect.relative: The element is positioned relative to its normal position in the document flow. You can usetop,bottom,left, andrightto offset it from where it would naturally sit, but its original space remains reserved in the layout. It also commonly acts as a reference container for elements styled withposition: absolute;.absolute: The element is positioned relative to its nearest positioned ancestor (an ancestor whosepositionis anything other thanstatic, usuallyrelative). It is removed from the normal document flow, meaning surrounding elements behave as if it does not exist.fixed: The element is positioned relative to the browser viewport and stays pinned in that spot even as you scroll. It is also removed from the normal flow.
Example in action:
Here, you would see a light gray box containing a smaller coral box in its top-right corner, positioned using absolute inside a relative container.
Code to try:
HTML:
<div class="contenedor">
<div class="absoluto">Posición absoluta</div>
Este es el contenido del contenedor relativo.
</div>
CSS:
.contenedor {
position: relative; /* Contenedor de referencia para el elemento absoluto */
width: 300px;
height: 150px;
background: #eee; /* Fondo gris claro */
margin: 15px auto; /* Centra horizontalmente */
border-radius: 6px; /* Bordes redondeados */
border: 1px solid #ccc; /* Borde sutil */
overflow: hidden; /* Oculta contenido que se desborde */
}
.absoluto {
position: absolute; /* Se posiciona respecto al contenedor relativo */
top: 10px; /* 10px desde el borde superior */
right: 10px; /* 10px desde el borde derecho */
background: coral; /* Fondo coral */
padding: 5px; /* Espacio interno */
border-radius: 4px; /* Bordes redondeados */
color: white; /* Texto blanco */
font-weight: bold; /* Texto en negrita */
font-size: 0.9em; /* Tamaño de fuente ligeramente menor */
}
7. Modern Layouts with Flexbox
How does it work?
Forget the complex layout hacks of the past: Flexbox (Flexible Box Layout) makes aligning and distributing items remarkably straightforward. It is a one-dimensional layout model, ideal for arranging elements in rows or columns—such as navbars, cards, or form controls. With Flexbox, you can easily manage free space distribution and alignment.
To get started, apply display: flex to the parent container. Properties set on that container (like justify-content or align-items) will directly govern its direct child elements, known as flex items.
Example in action:
Here, you would see a light gray container housing three darker gray boxes, spaced evenly and centered vertically, adapting smoothly if you resize the window.
Code to try:
HTML:
<div class="flex-container">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
CSS:
.flex-container {
display: flex; /* Convierte el contenedor en un contenedor flex */
justify-content: space-around; /* Distribuye el espacio horizontalmente alrededor de los ítems */
align-items: center; /* Centra los ítems verticalmente en el cross-axis */
background-color: #ddd;
padding: 10px;
border-radius: 6px;
margin: 15px 0;
flex-wrap: wrap; /* Permite que los ítems salten de línea si no caben */
}
.flex-container > div {
background-color: #aaa;
padding: 15px;
border-radius: 4px;
color: white;
font-weight: bold;
margin: 5px; /* Espacio entre ítems */
min-width: 80px; /* Evita que se aplasten demasiado */
text-align: center;
}
8. Advanced Layouts with CSS Grid
How does it work?
While Flexbox excels at handling either rows or columns, CSS Grid is your go-to tool for two-dimensional layouts, where you manage rows and columns simultaneously. Grid is perfect for building overall page architectures—combining headers, sidebars, main content areas, and footers into a clean grid system.
To use Grid, set display: grid; on the parent container. Next, define your columns (grid-template-columns) and rows (grid-template-rows) on the grid container. The direct children become grid items, snapping into the grid automatically or following manual placement rules.
Example in action:
Here, you would see a grid structured with cells arranged across rows and columns, containing numbered elements that adapt dynamically to the screen size.
Code to try:
HTML:
<div class="grid-container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
CSS:
.grid-container {
display: grid; /* Activa el modelo Grid */
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); /* Columnas dinámicas de al menos 100px */
gap: 10px; /* Espacio entre celdas */
margin: 15px 0; /* Margen externo */
}
.grid-container > div {
background-color: #8bc34a; /* Fondo verde claro */
padding: 20px; /* Espacio interno */
text-align: center; /* Texto centrado */
border-radius: 6px; /* Bordes redondeados */
color: white; /* Texto blanco */
font-weight: bold; /* Texto en negrita */
}
9. Pseudo-classes and Pseudo-elements
How do they work?
Pseudo-classes and pseudo-elements let you style scenarios beyond what basic tag, class, or ID selectors can reach.
- Pseudo-classes: (Prefix with a single colon
:) Select elements based on their state (e.g., when a link has been visited:visited, when hovered over with a mouse:hover, when an input is focused:focus) or based on structural position (e.g., the first child:first-child). - Pseudo-elements: (Prefix with a double colon
::) Allow you to target and style parts of an element that do not exist as distinct HTML nodes, or insert decorative content. The most common are::before(inserts content before the element) and::after(inserts content after it).
Example in action:
Here, you would see a link prepended with a “👉” emoji before the text, which changes color and adds an underline on hover, highlighting dynamic interaction.
Code to try:
HTML:
<a href="#" class="link-example">Enlace con pseudoclase (:hover) y pseudoelemento (::before)</a>
CSS:
.link-example {
text-decoration: none; /* Quita el subrayado por defecto */
color: #3498db; /* Azul inicial */
font-weight: bold; /* Texto en negrita */
transition: color 0.3s ease; /* Cambio suave de color */
}
.link-example:hover {
color: red; /* Cambia a rojo al pasar el mouse */
text-decoration: underline; /* Añade subrayado */
}
.link-example::before {
content: "👉 "; /* Añade una flecha antes del texto */
font-size: 0.9em; /* Ligeramente más pequeño */
}
10. Animations and Transitions
How do they work?
Adding motion to web pages can make them feel responsive, polished, and engaging. CSS provides two primary mechanisms to achieve this: transitions and animations. Both are great for enhancing user experience, such as highlighting buttons on hover or introducing smooth view transitions.
- Transitions: The simpler approach. They allow a CSS property (such as color or position) to interpolate smoothly between two states, such as during a mouse hover. You define which property to animate, the transition duration, and the timing function via the
transitionproperty. - Animations: More powerful and granular. Using
@keyframes, you define keyframe rules across various points in time, then bind that timeline to an element via theanimationproperty—controlling duration, iteration counts, direction, and easing.
Example in action:
Here, you would see a button that shifts color, lifts slightly, and refines its drop shadow on hover, utilizing smooth transitions for a natural feel.
Code to try:
HTML:
<button class="btn-transition">Botón con transición al pasar el mouse</button>
CSS:
.btn-transition {
background-color: #3498db; /* Azul inicial */
color: white; /* Texto blanco */
padding: 12px 24px; /* Espacio interno */
border: none; /* Sin borde */
border-radius: 6px; /* Bordes redondeados */
cursor: pointer; /* Cursor de mano al pasar el mouse */
font-size: 1rem; /* Tamaño de fuente */
margin-top: 10px; /* Margen superior */
display: inline-block; /* Comportamiento como bloque en línea */
font-weight: bold; /* Texto en negrita */
box-shadow: 0 2px 4px rgba(0,0,0,0.1); /* Sombra suave */
transition: background-color 0.3s ease, transform 0.1s ease, box-shadow 0.3s ease; /* Transiciones suaves */
}
.btn-transition:hover {
background-color: #2980b9; /* Azul más oscuro */
transform: translateY(-2px); /* Se eleva ligeramente */
box-shadow: 0 4px 8px rgba(0,0,0,0.2); /* Sombra más intensa */
}
.btn-transition:active {
background-color: #1f618d; /* Azul aún más oscuro al clic */
transform: translateY(0); /* Vuelve a su posición */
box-shadow: 0 2px 4px rgba(0,0,0,0.2); /* Sombra reducida */
}
11. CSS Variables (Custom Properties)
How do they work?
CSS variables (or custom properties) act as containers storing specific values (such as colors, sizes, or spacing units) to reuse throughout your stylesheet. This makes your styles significantly easier to maintain and update across large projects. For instance, modifying a single color variable updates every selector referencing it.
Variables are defined with names starting with -- (for example, --primary-color) and are typically declared inside the :root selector so they are accessible globally across the document. You reference them using the var(--variable-name) function.
Example in action:
Here, you would see elements sharing identical colors and box shadows defined through variables, illustrating how updating a single variable automatically cascades across the entire layout.
Code to try:
CSS:
:root {
--color-principal: #e74c3c; /* Rojo llamativo */
--espaciado-base: 15px; /* Espaciado estándar */
--sombra-ligera: 0 2px 4px rgba(0,0,0,0.1); /* Sombra suave */
}
h2 {
border-bottom: 2px solid var(--color-principal); /* Borde con el color variable */
}
.uses-variable {
color: var(--color-principal); /* Texto rojo *
border: 1px solid var(--color-principal); /* Borde rojo */
padding: 10px; /* Espacio interno */
margin: 10px 0; /* Margen externo */
border-radius: 4px; /* Bordes redondeados */
display: inline-block; /* Comportamiento como bloque en línea */
box-shadow: var(--sombra-ligera); /* Sombra variable */
}
12. Accessibility Best Practices in CSS
How do they work?
Web accessibility (or a11y) focuses on building websites usable by everyone, including people with visual, auditory, motor, or cognitive impairments. CSS plays an essential role in making your designs readable and navigable for all users. Keep these foundational practices in mind:
- Sufficient contrast: Ensure ample contrast between text and its background color so content is easily legible, particularly for users with low vision.
- Do not rely on color alone: Pair colors with text labels, icons, or bold styling to communicate states (such as errors, warnings, or success alerts).
- Scalable text: Use relative units like
remoremso users can scale base font sizes through their browser preferences. - Visible focus states: Ensure interactive elements (buttons, links, inputs) display a distinct visual outline when navigated via keyboard (the
:focusstate). Never strip theoutlinewithout replacing it with an equivalent, high-visibility alternative!
Example in action:
Here, you would see high-contrast text, status alerts styled with both bold text and color indicators, and elements displaying crisp focus rings when tabbed through with a keyboard.
Code to try:
HTML:
<button>Botón accesible</button>
<a href="#">Enlace accesible</a>
<p class="error-message">Error: Revisa los datos</p>
<p class="success-message">¡Éxito: Todo correcto!</p>
CSS:
body {
background-color: white; /* Fondo claro */
color: #222; /* Texto oscuro para buen contraste */
font-size: 1rem; /* Tamaño base escalable */
line-height: 1.5; /* Mejora la legibilidad */
}
button:focus,
a:focus,
input:focus,
select:focus,
textarea:focus {
outline: 2px solid blue; /* Contorno visible al enfocar */
outline-offset: 2px; /* Separa el contorno del elemento */
}
.error-message {
color: #e74c3c; /* Rojo para errores */
font-weight: bold; /* Negrita para no depender solo del color */
}
.success-message {
color: #2ecc71; /* Verde para éxito */
font-weight: bold; /* Negrita adicional */
}
13. CSS Organization and Scalability
How does it work?
As projects expand, structured CSS is vital for keeping code readable, maintainable, and scalable—especially across engineering teams. One widely adopted convention is the BEM methodology (Block, Element, Modifier), which relies on clean, predictable class naming conventions:
- Block: A standalone entity that is meaningful on its own (e.g.,
.card,.button,.header). - Element: A piece of a Block that depends on its parent context and has no standalone meaning (e.g.,
.card__title,.card__description,.header__logo). Connected to the Block name with a double underscore (__). - Modifier: A flag on a Block or Element used to change its appearance or state (e.g.,
.card--highlighted,.button--disabled,.header--fixed). Connected with a double hyphen (--).
BEM keeps your CSS predictable and prevents unintended cascading overrides in larger codebases.
Example in action:
Here, you would see two cards—one standard and one with a “highlighted” modifier—illustrating how .card, .card__title, .card__description, and .card--highlighted work together.
Code to try:
HTML:
<div class="card">
<h3 class="card__title">Título de la Tarjeta</h3>
<p class="card__description">Esta es una descripción corta.</p>
</div>
<div class="card card--highlighted">
<h3 class="card__title">Título de la Tarjeta Resaltada</h3>
<p class="card__description">Descripción de la tarjeta resaltada.</p>
</div>
CSS:
.card {
padding: 15px; /* Espacio interno */
border: 1px solid #ccc; /* Borde gris */
border-radius: 6px; /* Bordes redondeados */
margin-bottom: 15px; /* Espacio entre tarjetas */
background-color: #fff; /* Fondo blanco */
box-shadow: 0 2px 4px rgba(0,0,0,0.1); /* Sombra suave */
}
.card--highlighted {
border-color: #f39c12; /* Borde naranja */
background-color: #fcf8e3; /* Fondo amarillo claro */
box-shadow: 0 4px 8px rgba(0,0,0,0.08); /* Sombra más intensa */
}
.card__title {
font-weight: bold; /* Texto en negrita */
margin-top: 0; /* Sin margen superior */
margin-bottom: 8px; /* Margen inferior */
color: #2c3e50; /* Color oscuro */
}
.card__description {
font-size: 0.95em; /* Tamaño ligeramente menor */
color: #555; /* Gris oscuro */
margin-bottom: 0; /* Sin margen inferior */
}
Practice Resources and Next Steps
If you have made it this far, you have covered the core concepts of CSS needed to start styling your web projects. Remember: practice is what cements these skills. Here is how you can continue:
- Try out the examples: Check out the
index.htmlandstyles.cssfiles for this guide in my Gist. Copy them, open them in your code editor, and tweak colors, sizes, and positioning. Play around—breaking things and fixing them is part of learning! - Modify the examples: Change colors, sizes, and positions. Break layouts and rebuild them; it is the most effective way to learn.
- Build simple standalone projects: Try recreating a simple product card, a navigation bar, or a landing page section using Flexbox or Grid.
- Explore additional resources: CSS is deep and broad. Here are great places to continue your journey:
Keep going! CSS is both an essential technical skill and a creative outlet in web development. Keep practicing, experimenting, and building.