The src attribute is a fundamental HTML attribute used to specify the source of an external resource, such as images, scripts, or frames. It tells the browser where to find the file that it needs to load and display.
Key Points about the src Attribute:
-
Usage: The
srcattribute is commonly used in several HTML elements, including:<img>: To specify the source of an image.<script>: To link to an external JavaScript file.<iframe>: To define the source of an embedded frame.
-
File Path: The value of the
srcattribute is typically a URL or a relative path to the file. For example:<img src="images/photo.jpg" alt="A beautiful scenery"> <script src="script.js"></script> -
Loading Behavior: When the browser encounters an element with a
srcattribute, it will fetch the resource specified by the URL or path. For scripts, this means executing the JavaScript code; for images, it means displaying the image on the page. -
Relative vs. Absolute Paths:
- Relative Path: Points to a file relative to the location of the HTML file. For example,
src="script.js"assumesscript.jsis in the same directory as the HTML file. - Absolute Path: Specifies the full URL to the resource. For example,
src="https://example.com/script.js".
- Relative Path: Points to a file relative to the location of the HTML file. For example,
Example
Here’s a simple example demonstrating the src attribute in different contexts:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example of src Attribute</title>
</head>
<body>
<h1>Welcome to My Page</h1>
<!-- Image with src attribute -->
<img src="images/logo.png" alt="Logo">
<!-- External JavaScript file -->
<script src="script.js"></script>
</body>
</html>
Conclusion
The src attribute is essential for linking external resources to your HTML documents, enhancing the functionality and appearance of your web pages. If you have more questions or need further clarification, feel free to ask!
