--- title: Definire gli stili dei link slug: Learn/CSS/Styling_text/Definire_stili_link translation_of: Learn/CSS/Styling_text/Styling_links ---
Quando si vogliono assegnare degli stili ai link, è importante capire come fare uso delle pseudo-classi per definire efficacemente gli stili dei vari stati dei link, e come attribuire gli stili ai link per il loro uso nei più comuni elementi di interfaccia, come i menu di navigazione e le schede. Nel seguente articolo illustreremo tutti questi argomenti.
Prerequisiti: | Conoscenza informatica di base, elementi di HTML (leggi Introduction to HTML), elementi di CSS (leggi Introduction to CSS), Fondamenti di testo e font con CSS. |
---|---|
Obbiettivo: | Imparare a definire gli stili degli stati dei link, e come utilizzarli efficacemente per i più comuni elementi di interfaccia come i menu di navigazione. |
Abbiamo visto come i link possano essere impiegati nel tuo codice HTML in accordo con le best practices viste in Creare gli hyperlink. Nell'articolo aumenteremo ulteriormente questa conoscenza, mostrandoti le best practices per la definizione degli stili dei link.
La prima cosa da capire è il concetto di stato dei link — esistono stati differenti dei link, ai quali è possibile attribuire gli stili utilizzando differenti pseudo-classi:
L'esempio seguente mostra il comportamento predefinito di un link (in questo caso il CSS aumenta il font e centra il testo per risaltarlo maggiormente).
<p><a href="#">A simple link</a></p>
p { font-size: 2rem; text-align: center; }
{{ EmbedLiveSample('Default_styles', '100%', 120) }}
Nota: Tutti i link inseriti negli esempi della pagina sono simulati — sono stati inseriti i simboli #
(cancelletto) o $ (sterlina) al posto dell'URL reale. Questo perché se fossero inclusi gli URL reali, cliccando su di essi, si interromperebbero gli esempi (si potrebbe verificare un errore, o caricare una pagina da cui non si potrebbe tornare indietro). Il #
(cancelletto) invece si connette esclusivamente alla pagina corrente.
Quando esplorerete gli stili predefiniti, si noteranno alcune cose:
E' abbastanza interessante il fatto che questi stili predefiniti sono relativamente gli stessi rispetto a quelli usciti nei primi tempi dei browser verso la metà degli anni 90. Questo perché gli utenti conoscono e si aspettano questo comportamento — se i link avessero stili differenti da questi, confonderebbero un sacco di persone. Questo non significa che non si debbano definire gli stili del tutto, ma solo che non ci si deve allontanare troppo dalla visualizzazione che gli utenti si aspettano. Si dovrebbe almeno:
Gli stili predefiniti possono essere modificati o disattivati utilizzando le seguenti proprietà dei CSS:
Nota: tu non sei limitato alle suddette proprietà per definire gli stili dei tuoi link — sentiti libero di utilizzare le proprietà che più ti piacciono. Cerca solo di non diventare troppo fantasioso !
Ora che abbiamo visto qualche dettaglio sugli stati predefiniti, diamo uno sguardo ad un tipico set di stili dei link.
Per cominciare, scriviamo il nostro set di stili vuoto:
a { } a:link { } a:visited { } a:focus { } a:hover { } a:active { }
Questo ordine è importante perché gli stili dei link si sovrappongono l'uno sull'altro, per esempio gli stili definiti nella prima regola si applicheranno a tutti quelli seguenti, e quando si attiva un link, ci si passa anche sopra con il mouse. Se si indicano nell'ordine sbagliato, le cose potrebbero non lavorare nel verso giusto. Per ricordare questo ordine, si può provare ad usare, come aiuto mnemonico, LoVe Fears HAte.
Adesso si aggiungano alcune altre impostazioni per una appropriata definizione degli stili:
body { width: 300px; margin: 0 auto; font-size: 1.2rem; font-family: sans-serif; } p { line-height: 1.4; } a { outline: none; text-decoration: none; padding: 2px 1px 0; } a:link { color: #265301; } a:visited { color: #437A16; } a:focus { border-bottom: 1px solid; background: #BAE498; } a:hover { border-bottom: 1px solid; background: #CDFEAA; } a:active { background: #265301; color: #CDFEAA; }
Forniamo anche il seguente esempio HTML a cui applicare il CSS:
<p>There are several browsers available, such as <a href="#">Mozilla Firefox</a>, <a href="#">Google Chrome</a>, and <a href="#">Microsoft Edge</a>.</p>
Mettendoli insieme il risultato sarà questo:
{{ EmbedLiveSample('Styling_some_links', '100%', 150) }}
Quindi che cosa abbiamo fatto qui? Il risultato è certamente differente rispetto allo stile predefinito, ma propone ancora un'esperienza abbastanza familiare per gli utenti che sanno cosa sta succedendo:
a
per sbarazzarsi della sottolineatura del testo e dell'outline per il focus (che comunque variano a seconda dei browser) , ed aggiunge una piccola quantità di padding ad ogni link — tutto questo diventerà chiaro più avanti.a:link
e a:visited
per impostare una coppia di variazioni dei colori sui link dei visitati e non visitati, così sono distinti.a:focus
ea:hover
per impostare i link del focus e del passaggio del mouse in modo da avere differenti colori di background, più una sottolineatura per evidenziare ulteriormente il link. Qui sono due i punti da notare:
1px solid
, senza indicare un colore. In questo modo, il bordo adotta lo stesso colore del testo dell'elemento, ed è utile in quei casi in cui il testo usa un colore differente per ciascun caso.a:active
imposta i link con uno schema di colore invertito quando sono attivati, per render chiaro che sta succedendo qualcosa di importante!In questa sessione di active learning, ci piacerebbe che tu prendessi il nostro set di regole vuoto e aggiungessi le tue dichiarazioni per rendere i link veramente mitici. Usa la tua immaginazione e scatenati. Siamo sicuri che ti potrà venire in mente qualcosa di più fantasioso e funzionale rispetto al nostro esempio sopra.
Se fai un errore, puoi sempre ripartire usando il pulsante Reset. E se rimani bloccato, clicca sul bottone Show solution per inserire l'esempio che ti abbiamo mostrato sopra.
<div class="body-wrapper" style="font-family: 'Open Sans Light',Helvetica,Arial,sans-serif;"> <h2>HTML Input</h2> <textarea id="code" class="html-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"><p>There are several browsers available, such as <a href="#">Mozilla Firefox</a>, <a href="#">Google Chrome</a>, and <a href="#">Microsoft Edge</a>.</p></textarea> <h2>CSS Input</h2> <textarea id="code" class="css-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">a { } a:link { } a:visited { } a:focus { } a:hover { } a:active { }</textarea> <h2>Output</h2> <div class="output" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"></div> <div class="controls"> <input id="reset" type="button" value="Reset" style="margin: 10px 10px 0 0;"> <input id="solution" type="button" value="Show solution" style="margin: 10px 0 0 10px;"> </div> </div>
var htmlInput = document.querySelector(".html-input"); var cssInput = document.querySelector(".css-input"); var reset = document.getElementById("reset"); var htmlCode = htmlInput.value; var cssCode = cssInput.value; var output = document.querySelector(".output"); var solution = document.getElementById("solution"); var styleElem = document.createElement('style'); var headElem = document.querySelector('head'); headElem.appendChild(styleElem); function drawOutput() { output.innerHTML = htmlInput.value; styleElem.textContent = cssInput.value; } reset.addEventListener("click", function() { htmlInput.value = htmlCode; cssInput.value = cssCode; drawOutput(); }); solution.addEventListener("click", function() { htmlInput.value = htmlCode; cssInput.value = 'p {\n font-size: 1.2rem;\n font-family: sans-serif;\n line-height: 1.4;\n}\n\na {\n outline: none;\n text-decoration: none;\n padding: 2px 1px 0;\n}\n\na:link {\n color: #265301;\n}\n\na:visited {\n color: #437A16;\n}\n\na:focus {\n border-bottom: 1px solid;\n background: #BAE498;\n}\n\na:hover {\n border-bottom: 1px solid;\n background: #CDFEAA;\n}\n\na:active {\n background: #265301;\n color: #CDFEAA;\n}'; drawOutput(); }); htmlInput.addEventListener("input", drawOutput); cssInput.addEventListener("input", drawOutput); window.addEventListener("load", drawOutput);
{{ EmbedLiveSample('Playable_code', 700, 800) }}
Una pratica comune consiste nell'includere le icone sui link, per fornire più di un indicatore per quanto riguarda il tipo di contenuto a cui punta il link. Vediamo sotto un esempio molto semplice che associa un'icona ad un link esterno (sono i link che collegano ad altri siti). In genere tale icona è rappresentata come una piccola freccia che indica fuori da un box — per questo esempio, useremo il grande esempio fornito da icons8.com.
Guardiamo l'HTML e il CSS che ci daranno l'effetto che vogliamo. Per prima cosa, abbiamo del semplice HTML da definire:
<p>For more information on the weather, visit our <a href="#">weather page</a>, look at <a href="#">weather on Wikipedia</a>, or check out <a href="#">weather on Extreme Science</a>.</p>
Quindi il CSS:
body { width: 300px; margin: 0 auto; font-family: sans-serif; } p { line-height: 1.4; } a { outline: none; text-decoration: none; padding: 2px 1px 0; } a:link { color: blue; } a:visited { color: purple; } a:focus, a:hover { border-bottom: 1px solid; } a:active { color: red; } a[href*="http"] { background: url('https://mdn.mozillademos.org/files/12982/external-link-52.png') no-repeat 100% 0; background-size: 16px 16px; padding-right: 19px; }
{{ EmbedLiveSample('Including_icons_on_links', '100%', 150) }}
So what's going on here? We'll skip over most of the CSS, as it's just the same information you've looked at before. The last rule however is interesting — here we are inserting a custom background image on external links in a similar manner to how we handled custom bullets on list items in the last article — this time however we are using {{cssxref("background")}} shorthand instead of the individual properties. We set the path to the image we want to insert, specify no-repeat
so we only get one copy inserted, and then specify the position as 100% of the way over to the right of the text content, and 0 pixels from the top.
We also use {{cssxref("background-size")}} to specify the size we want the background image to be shown at — it is useful to have a larger icon and then resize it like this as needed for responsive web design purposes. This does however only work with IE 9 and later, so if you need to support those older browsers, you'll just have to resize the image and insert it as is.
Finally, we set some {{cssxref("padding-right")}} on the links to make space for the background image to appear in, so we aren't overlapping it with the text.
A final word — how did we select just external links? Well, if you are writing your HTML links properly, you should only be using absolute URLs for external links — it is more efficient to use relative links to link to other parts of your own site. The text "http" should therefore only appear in external links, and we can select this with an attribute selector: a[href*="http"]
selects {{htmlelement("a")}} elements, but only if they have an {{htmlattrxref("href","a")}} attribute with a value that contains "http" somewhere inside it.
So that's it — try revisiting the active learning section above and trying this new technique out!
Note: Don't worry if you are not familiar with backgrounds and responsive web design yet; these are explained in other places.
The tools you've explored so far in this article can also be used in other ways. For example, states like hover can be used to style many different elements, not just links — you might want to style the hover state of paragraphs, list items, or other things.
In addition, links are quite commonly styled to look and behave like buttons in certain circumstances — a website navigation menu is usually marked up as a list containing links, and this can be easily styled to look like a set of control buttons or tabs that provide the user with access to other parts of the site. Let's explore how.
First, some HTML:
<ul> <li><a href="#">Home</a></li><li><a href="#">Pizza</a></li><li><a href="#">Music</a></li><li><a href="#">Wombats</a></li><li><a href="#">Finland</a></li> </ul>
And now our CSS:
body,html { margin: 0; font-family: sans-serif; } ul { padding: 0; width: 100%; } li { display: inline; } a { outline: none; text-decoration: none; display: inline-block; width: 19.5%; margin-right: 0.625%; text-align: center; line-height: 3; color: black; } li:last-child a { margin-right: 0; } a:link, a:visited, a:focus { background: yellow; } a:hover { background: orange; } a:active { background: red; color: white; }
This gives us the following result:
{{ EmbedLiveSample('Styling_links_as_buttons', '100%', 100) }}
Let's explain what's going on here, focusing on the most interesting parts:
inline-block
— {{htmlelement("a")}} elements are inline by default and, while we don't want them to spill onto their own lines like a value of block
would achieve, we do want to be able to size them. inline-block
allows us to do this.<ul>
and fall down to the next line. However, we take it back down to 100% using the next rule, which selects only the last <a>
in the list, and removes the margin from it. Done!Note: You may have noticed that the list items in the HTML are all put on the same line as each other — this is done because spaces/line breaks in between inline block elements create spaces on the page, just like the spaces in between words, and such spaces would break our horizontal navigation menu layout. So we've removed the spaces. You can find more information about this problem (and solutions) at Fighting the space between inline block elements.
We hope this article has provided you with all you'll need to know about links — for now! The final article in our Styling text module details how to use custom fonts on your websites, or web fonts as they are better known.
{{PreviousMenuNext("Learn/CSS/Styling_text/Styling_lists", "Learn/CSS/Styling_text/Web_fonts", "Learn/CSS/Styling_text")}}