OneBite.Dev - Coding blog in a bite size

apply css in html

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

Applying CSS in HTML

Utilizing Cascading Style Sheets (CSS) is a fundamental skill in web development. In this article, we’ll discuss how to apply CSS to your HTML files to make your websites more appealing and functional.

Code Snippet for Applying CSS in HTML

<!DOCTYPE html>
<html>
<head>
    <style>
        body {
            background-color: lightblue;
        }
        h1 {
            color: navy;
            margin-left: 30px;
        }
    </style>
</head>
<body>
    <h1>This is a Heading</h1>
</body>
</html>

Code Explanation for Applying CSS in HTML

Let’s break down this code to understand how CSS is applied in HTML:

  1. DOCTYPE html: This is the document type declaration and it is used to tell the browser that the document is an HTML5 document.

  2. html: This is the root of the HTML document.

  3. head: This element represents a container for metadata (data about data) and it is always placed between the <html> and <body> tags.

  4. style: CSS is placed inside the <style> tags. This is one of the ways to include CSS in your HTML files known as internal styling.

  5. body: Inside the <style> tag, we declare styles for the body and h1 tags. For the body, we set a light blue background color.

  6. h1: For the h1 tag, we set the text color to navy and pushed the heading 30 pixels from the left margin.

  7. After the head section, we move to the body section where the actual content of the web page resides. Here, we simply have a heading defined by the h1 tag and the styling for this tag has been defined in the style section of the head.

This is a simple example of implementing CSS styling in your HTML files, making your web page look more attractive. You may specify as many style definitions as required within the style block for different elements.

css