Come Aggiungere Stili CSS a una Pagina HTML: Guida per Principianti | How to Add CSS Styles to an HTML Page: A Beginner's Guide

Roberto Celano - Sep 4 - - Dev Community

Introduzione | Introduction

Italiano: Questo articolo è disponibile sia in italiano che in inglese. Scrolla verso il basso per la versione in inglese.
English: This article is available in both Italian and English. Scroll down for the English version.


Versione Italiana

Come Aggiungere Stili CSS a una Pagina HTML: Guida per Principianti

Immagina di essere in cucina, pronto a preparare un piatto. Hai gli ingredienti principali (HTML) davanti a te: carne, verdure, spezie. Ma per trasformare questi ingredienti in un capolavoro culinario, hai bisogno di tecniche di cottura, condimenti e impiattamento ed è qui che entra in gioco il CSS (Cascading Style Sheets). Il CSS è come la tua "arte del condimento" per il web: senza di esso, la tua pagina HTML sarebbe nutriente ma un po' insipida. In questa guida, esploreremo come "condire" il tuo sito web usando il CSS per trasformare una semplice struttura HTML in una pagina visivamente accattivante e armoniosa.


Cos'è il CSS?


Il CSS, o Cascading Style Sheets, è il "libro delle ricette" per il design del web. Proprio come in cucina, dove puoi utilizzare diverse tecniche di cottura per ottenere sapori unici, il CSS ti consente di stilizzare la tua pagina HTML in modi infiniti.


Breve storia del CSS: Nato negli anni '90, il CSS ha rivoluzionato il modo in cui le pagine web vengono progettate separando la "struttura" (HTML) dalla "presentazione" (CSS).


Esempi di utilizzo del CSS


Proprio come puoi aggiungere un tocco di colore al tuo piatto con un po' di salsa, con il CSS puoi colorare i testi, disporre gli elementi in modo creativo e aggiungere un tocco artistico alla tua pagina web.


Metodi per aggiungere CSS a una pagina HTML


Ci sono tre metodi principali per aggiungere il CSS alla tua pagina HTML, proprio come ci sono diversi modi per preparare un piatto in cucina. Ogni metodo ha vantaggi e svantaggi a seconda delle esigenze del progetto.

INLINE CSS

È come aggiungere un pizzico di sale direttamente al piatto: funziona per piccole modifiche di stile, ma non è ideale se devi condire un intero banchetto.

Esempio:

<p style="color: blue;">Testo blue;</p>;
Enter fullscreen mode Exit fullscreen mode


Pro:
Facile da usare e rapido per piccole modifiche.
Contro: Difficile da mantenere in progetti di grandi dimensioni, può creare confusione se utilizzato troppo spesso.


CSS INTERNO

È più simile a marinare un ingrediente specifico in una ciotola prima di cucinarlo. Usi uno stile specifico per una singola pagina, ma tutte le modifiche devono essere fatte in quel documento.

Esempio:

<style>
  p {
    color: blue;
  }
</style>
Enter fullscreen mode Exit fullscreen mode


Pro:
Tutti gli stili sono in un unico posto, facili da controllare.
Contro: Applicabile solo a una pagina, non ideale per siti web con più pagine.


CSS ESTERNO

Questo è come preparare una salsa speciale in un barattolo e usarla per diversi piatti: un foglio di stile separato che puoi applicare a tutte le pagine del tuo sito.

Esempio:

<link rel="stylesheet" href="styles.css">
Enter fullscreen mode Exit fullscreen mode


Pro:
Riutilizzabile, facile da gestire, ottimo per siti web di grandi dimensioni.
Contro: Richiede la gestione di più file, ma è un piccolo prezzo da pagare per la versatilità.

Proprio come seguire una ricetta, i CSS hanno una sintassi di base che devi conoscere per creare un design perfetto.


I Selettori

I selettori sono gli "ingredienti" specifici che vuoi stilizzare. Puoi selezionare tutti gli elementi di un certo tipo (es. p per i paragrafi), usare una classe (.class-name) o un ID (#id-name).

Esempio:

p {
  color: red;
}

.highlight {
  background-color: yellow;
}

#main-title {
  font-size: 2em;
}
Enter fullscreen mode Exit fullscreen mode


Proprietà e Valori

Le proprietà sono come le spezie: specificano cosa vuoi modificare (es. colore, dimensione del carattere), mentre i valori sono la quantità o il tipo di spezia che stai utilizzando (es. rosso, 16px).

Esempio:

p {
  color: red; /* Proprietà: colore, Valore: rosso */
}
Enter fullscreen mode Exit fullscreen mode


Creare un foglio di stile esterno

Ora che hai compreso la sintassi di base, è il momento di creare il tuo "barattolo di salsa segreta": un foglio di stile esterno che puoi applicare a tutte le tue pagine HTML.

Passaggi per creare un foglio di stile esterno


Crea un nuovo file chiamato styles.css.

Inizia a scrivere i tuoi stili:

body {
  font-family: Arial, sans-serif;
  background-color: #f4f4f4;
}

h1 {
  color: #333;
  text-align: center;
}

p {
  line-height: 1.6;
}
Enter fullscreen mode Exit fullscreen mode


Collega il file CSS alla tua pagina HTML utilizzando il tag <link> nell' <head>

<link rel="stylesheet" href="styles.css">
Enter fullscreen mode Exit fullscreen mode


Aggiunta di CSS alla tua pagina HTML:

Ecco un esempio pratico di come combinare una semplice pagina HTML con un foglio di stile esterno per creare un "piatto" finito.

HTML:

<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>La mia prima pagina con lo style</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Benvenuto nella mia cucina web</h1>
    <p>Questa è la mia prima pagina HTML con lo style!</p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
}

h1 {
    color: #333;
    text-align: center;
}

p {
    line-height: 1.6;
}
Enter fullscreen mode Exit fullscreen mode


Migliori pratiche

Per diventare un vero "chef del web", ecco alcune best practices da seguire

Usa nomi di classi significativi: Come una ricetta ben scritta, i nomi delle classi dovrebbero descrivere chiaramente il loro scopo.

Organizza il tuo foglio di stile: Mantieni il codice pulito e commentato, proprio come una cucina ordinata e ben organizzata.

Evita l'uso eccessivo del CSS inline: Proprio come non esagereresti con il sale, evita di applicare troppi stili inline e preferisci i fogli di stile esterni per una migliore manutenibilità.


Conclusione

Il CSS è il tocco finale che trasforma una semplice struttura HTML in un capolavoro visivo. Proprio come in cucina, con un po' di pratica e creatività, puoi usare il CSS per "condire" il tuo sito web e renderlo unico. Quindi, prendi il tuo "barattolo di spezie" e inizia a sperimentare con i tuoi stili!


English Version

How to Add CSS Styles to an HTML Page: A Beginner's Guide

Imagine you're in the kitchen, ready to prepare a dish. You have the main ingredients (HTML) in front of you: meat, vegetables, spices. But to transform these ingredients into a culinary masterpiece, you need cooking techniques, seasonings, and plating – and this is where CSS (Cascading Style Sheets) comes into play. CSS is like your "seasoning art" for the web: without it, your HTML page would be nutritious but a bit bland.In this guide, we'll explore how to "season" your website using CSS to transform a simple HTML structure into a visually appealing and harmonious page.


What is CSS?


The CSS, or Cascading Style Sheets, is the "recipe book" for web design. Just like in the kitchen, where you can use different cooking techniques to achieve unique flavors, CSS allows you to style your HTML page in countless ways.


Brief history of CSS: Born in the 1990s, CSS revolutionized the way web pages are designed by separating "structure" (HTML) from "presentation" (CSS).


Examples of CSS usage


Just as you can add a touch of color to your dish with some sauce, with CSS you can color texts, arrange elements creatively, and add an artistic touch to your webpage.


Methods to Add CSS to an HTML Page


There are three main methods to add CSS to your HTML page, just like there are different ways to prepare a dish in the kitchen. Each method has its advantages and disadvantages depending on the project’s needs.

INLINE CSS

It's like adding a pinch of salt directly to your dish: it works for small style tweaks but is not ideal if you need to season an entire feast.

Example:

<p style="color: blue;">Blue text</p>
Enter fullscreen mode Exit fullscreen mode


Pros:
Easy to use and quick for small changes.
Cons: Difficult to maintain in large projects, can create confusion if used too often.


INTERNAL CSS:

This is more like marinating a specific ingredient in a bowl before cooking it. You use a specific style for a single page, but all changes must be made in that document.

Example:

<style>
  p {
    color: blue;
  }
</style>
Enter fullscreen mode Exit fullscreen mode


Pros:
All styles are in one place, easy to control.
Cons: Applicable only to one page, not ideal for multipage websites.


EXTERNAL CSS:

This is like preparing a special sauce in a jar and using it for different dishes: a separate style sheet that you can apply to all pages of your site.

Example:

<link rel="stylesheet" href="styles.css">
Enter fullscreen mode Exit fullscreen mode


Pros:
Reusable, easy to manage, great for large websites.
Cons: Requires managing multiple files, but that’s a small price to pay for versatility.

Just like following a recipe, CSS has its basic syntax that you need to know to cook up a perfect design.


Selectors

Selectors are the specific "ingredients" you want to style. You can select all elements of a certain type (ex. p for paragraphs), use a class (.class-name), or an ID (#id-name).

Example:

p {
  color: red;
}

.highlight {
  background-color: yellow;
}

#main-title {
  font-size: 2em;
}
Enter fullscreen mode Exit fullscreen mode


Properties and Values

Properties are like spices: they specify what you want to modify (ex. color, font-size), while values are the amount or type of spice you’re using (ex. red, 16px).

Example:

p {
  color: red; /* Property: color, Value: red */
}
Enter fullscreen mode Exit fullscreen mode


Creating an external style sheet

Now that you understand the basic syntax, it’s time to create your "secret sauce jar" – an external style sheet that you can apply to all your HTML pages.

Steps to create an external style sheet


Create a new file called styles.css .

Start writing your styles:

body {
  font-family: Arial, sans-serif;
  background-color: #f4f4f4;
}

h1 {
  color: #333;
  text-align: center;
}

p {
  line-height: 1.6;
}
Enter fullscreen mode Exit fullscreen mode


Link the CSS file to your HTML page using the <link> tag in the <head>

<link rel="stylesheet" href="styles.css">
Enter fullscreen mode Exit fullscreen mode


Adding CSS to Your HTML Page:

Here’s a practical example of how to combine a simple HTML page with an external style sheet to create a finished "dish."

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My First Styled Page</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Welcome to My Web Kitchen</h1>
    <p>This is my first HTML page with style!</p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
}

h1 {
    color: #333;
    text-align: center;
}

p {
    line-height: 1.6;
}
Enter fullscreen mode Exit fullscreen mode


Best practices

To become a true "web chef", here are some best practices to follow

Use meaningful class names:
Like a well-written recipe, class names should clearly describe their purpose.

Organize your style sheet:
Keep your code clean and commented, just like a tidy and well-organized kitchen.

Avoid excessive inline CSS:
Just as you wouldn’t overdo the salt, avoid applying too many inline styles and prefer external style sheets for better maintainability.


Conclusion

CSS is the final touch that transforms a simple HTML structure into a visual masterpiece. Just like in cooking, with a little practice and creativity, you can use CSS to "season" your website and make it unique. So grab your "spice jar" and start experimenting with your styles!


Traduzione:
Questo articolo è stato tradotto con l'ausilio di strumenti di traduzione professionali.
This article was translated with the help of professional translation tools.

. . .
Terabox Video Player