• Home
  • CSS
  • Styling chosen links on site, e.g only links to PDF file

Styling chosen links on site, e.g only links to PDF file



In previous post: styling lists with pseudo-classes I described how to change the color of active, clicked or hovered links. Now I will show you how to change the style of selected links, e.g. only those that lead to PDF files.

Let’s assume that we have several links on our site. Some of them lead to other pages, and some to PDF files. We want to change the appearance of only those links that lead to PDF files. We can do this by adding the appropriate class to each link in HTML, but we can also do it faster by using the a [href = “something”] tag in css.

.html

<div>
	<a href="https://love-coding.pl/pytania-rekrutacyjne/pl/">link to site</a><br>
	<a href="https://love-coding.pl/pytania-rekrutacyjne/basic_git_commands_pl.pdf">link to PDF file</a><br>
	<a href="https://love-coding.pl/pytania-rekrutacyjne/pl/">link to site</a><br>
	<a href="https://love-coding.pl/pytania-rekrutacyjne/basic_git_commands_en.pdf">link to PDF file</a><br>
	<a href="https://love-coding.pl/pytania-rekrutacyjne/pl/">link to site</a><br>
</div>

.css

a[href$=".pdf"] {
     background: url("https://love-coding.pl/blog/cwiczenia/img/pdf-icon-20.png") 
     0 50% no-repeat; 
     padding-left: 20px;
     color: blue;
 }


The $ = operator means that we select all links which names ends with “.pdf”.

As a result, for all links referring to PDF we received a specific appearance: blue links color and a PDF icon inserted before the link:



In the same way, we can change the color of links that lead to a specific page, e.g. to Facebook or YouTube:

<div>
	<a href="https://www.youtube.com/channel/UCz5Ed7-7pEfCAuxbs-3WIdA">link to youtube</a><br>
</div>
a[href*="youtube"] {
     color: red;
 }

Effect:



Similarly, different styles can also be set for selected images:

<img src="https://love-coding.pl/blog/cwiczenia/img/pdf-icon-100.png">
img[src*="icon"] {
  border: 2px solid gray;
}

Joanna

Leave a Reply

Your email address will not be published. Required fields are marked *