I just started with the html course and have been following when we use href and when we use src to attach something. But can someone explain to me the difference between them and thus why they cannot be used interchangeably?
Welcome to the forum
If you’re talking about the difference between including a CSS file and including a JS file that bothers me as well.
<link rel="stylesheet" href="styles.css">
<script src="myscripts.js"></script>
Why so different…
The short answer is that this is just the way it is. There is probably a reason or history for this if you dig, I don’t know it though.
If you’re talking about something else, then you’ll need to explain what you’re talking about.
Welcome to the forum @gsim
The src
attribute is used to embed code from a source. Which is why it is used for the script
element. For example, JavaScript needs to be loaded inside the script
element. You could take JavaScript code and place it in a script
element, and it will still work. However, best practice is separate HTML from JS. This is why it is also used for the img
element. You need to load the image or picture into the HTML for it to render.
The href
attribute, hyperlink reference, points to a URL resource.
For a stylesheet, the resource is a CSS file. Which is why the href
attribute is used in a link
element. The CSS does not need to load in the HTML, it just needs a reference to a stylesheet. This is why it also used in the anchor element. In an anchor element, the resource could be either internal (where you click on a link and are taken to another section of the same web page) or external (a new webpage) to the current HTML.
A href
resource is like a library. You can use the href
attribute to point to something, but it will not affect the functionality of the HTML. If you don’t have a link
,style
, or anchor elements (or the filenames are misspelled) the HTML will look vanilla, but it will still render.
A src
source is like a fountain. You can use the src
attribute for JavaScript or to show an image. Without the src
attribute, a visitor may not see the effect of the fountain.
Happy coding
Great explanation, thanks.
Still though, this looks pretty good to me:
<style src="style.css"></style>
<script src="script.css"></script>
More on this here: https://css-tricks.com/why-isnt-it-style-src/
or this:
<link rel="script" href="script.js">
<link rel="stylesheet" href="styles.css">