OneBite.Dev - Coding blog in a bite size

insert css in html

Code snippet for how to insert css in html with sample and detail explanation

Insert CSS in HTML

Cascading Style Sheets (CSS) is a vital tool in web development, significantly enhancing the website’s appearance. This article will guide you through the process of incorporating CSS into HTML to provide an upgraded user interface for your site visitors.

Code snippet ‘Insert CSS in HTML’

Incorporating CSS into HTML can be achieved in three primary ways. You can use Internal CSS, Inline CSS, or External CSS. Let’s look at examples of each.

  1. Internal CSS: This method involves including the CSS code inside the <style> tag in the <head> tag of your HTML.
<!DOCTYPE html>
<html>
<head>
<style>
    body {background-color: powderblue;}
    h1   {color: blue;}
    p    {color: red;}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>
  1. Inline CSS: This method uses the style attribute within the HTML tag.
<!DOCTYPE html>
<html>
<body>

<h1 style="color:blue;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>

</body>
</html>
  1. External CSS: This method involves creating a separate .css file and linking it in your HTML file.

In your style.css file:

body {background-color: powderblue;}
h1 {color: blue;}
p    {color: red;}

And in your HTML file:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

Code Explanation for ‘Insert CSS in HTML’

  1. Internal CSS: With this method, the styles only apply to the single HTML file where the CSS code is embedded. It is practical for single-page websites. The CSS code is placed within the <style> tags in the HTML <head> tag.

  2. Inline CSS: Using this method, you can apply styles directly to a particular HTML element. The style attribute in the HTML tag is used for this purpose. While it provides increased control over individual elements, it might lead to messy code if used excessively.

  3. External CSS: Creating a separate .css file and linking it to your HTML file does this. This method allows the same code to be reused across multiple HTML files, making it easier to maintain large websites. The link to the .css file is provided in the <head> tag using the <link> tag. Ensure the correct pathname to the .css file is given.

By implementing these methods, you can swiftly incorporate CSS in HTML, significantly improving the aesthetic appeal of your websites. Remember, aesthetics is key in UI/UX design and can greatly influence traffic and dwell time on your website.

css