Back to blog

September 07, 2024

avataravatar

Gautam Patoliya, Deep Poradiya

Tutor Head

Linking CSS and JavaScript to HTML Documents

blog-img-Linking CSS and JavaScript to HTML Documents
  • Linking CSS and JavaScript files to an HTML document is essential for adding styling and interactivity to a webpage.


[A]. Linking CSS


  • You can link an external CSS file to an HTML document using the <link> element. The <link> element is placed inside the <head> section of the HTML document.


  • Example:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Linking CSS Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Welcome to My Website</h1>
<p>This is a paragraph styled with external CSS.</p>
</body>
</html>


In this example:


  • The <link> element has an href attribute that points to the styles.css file.


  • The rel="stylesheet" attribute specifies that the linked file is a stylesheet.


  • The CSS file (styles.css) contains the styles that will be applied to the HTML elements.


  • Example


  • styles.css:


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

h1 { color: #333; }

p { color: #666; }


[B]. Linking JavaScript


  • You can link an external JavaScript file to an HTML document using the <script> element. The <script> element can be placed either in the <head> section or just before the closing </body> tag.


  • Example:



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Linking JavaScript Example</title><link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Welcome to My Website</h1>
<button id="myButton">Click Me</button>

<script src="script.js"></script> </body> </html>


In this example:


  • The <script> element has a src attribute that points to the script.js file.


  • The script.js file contains JavaScript code that will be executed when the webpage loads.


  • The <script> tag is placed just before the closing </body> tag to ensure that the HTML content loads before the JavaScript is executed.


  • Example


  • script.js:


document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});

HTML
CSS
JavaScript