OneBite.Dev - Coding blog in a bite size

override css

Code snippet for how to override css with sample and detail explanation

Overriding CSS

When it comes to enriching the aesthetics of a website, making sure the display properties align with the desired visual impact, CSS (Cascading Style Sheets) is an integral part of the web development process. However, there can be scenarios where the current CSS rules may not meet some specific requirements, in such cases, overriding CSS becomes essential.

Code Snippet

Let’s learn how to override CSS through a simple code snippet. Suppose we have a webpage with a paragraph text and the CSS rule sets its color as black. Now, we want to override this rule and instead set the text color as blue.

<!DOCTYPE html>
<html>
<head>
    <style>
        p {
            color: black;
        }
    </style>
</head>
<body>

<p id="para">Welcome! This is a sample paragraph.</p>

<script>
    document.getElementById('para').style.color = 'blue';
</script>

</body>
</html>

Code Explanation

This tutorial is divided into four parts corresponding to the four sections of the code: ‘head’, ‘style’, ‘p’, and ‘script’.

  1. <head> <style>: These tags contain the CSS rules that are applied to the entire HTML document. Here, we have set all paragraph (‘p’) text color to be ‘black’.

  2. <body>: This is the main section of the webpage.

  3. <p id="para">: This is a paragraph in the webpage’s body, with an ID ‘para’. IDs are unique identifiers used to select and manipulate a specific HTML element through a scripting language like JavaScript.

  4. <script>: Finally, the script tag contains the JavaScript code. This code gets the paragraph element by its ID and changes its color to blue, thus overriding the initial CSS rule. The line document.getElementById('para').style.color = 'blue'; tells the browser: “Take the HTML element that has the id of ‘para’ and change its text color to blue.”

Just like that, you’ve successfully overridden the CSS of an HTML element using JavaScript. Note that this approach can be extended to override any CSS property, not just color. Also, besides JavaScript, you could equally override CSS using inline CSS or !important declarations, although these should be used sparingly to avoid making your code too complex and hard to debug.

css