Reputation: 1
Let look at the following codes as example.
var tst;
tst = document.getElementsByClassName("tst");
tst.style.backgroundColor = "#008000";
tst.style.marginTop = "50px";
tst.innerHTML = "Testing an element.";
body {
font-size: 0px;
padding: 0px;
margin: 0px;
width: 100%;
overflow-x: hidden;
}
.tst {
font-family: Arial;
font-size: 20px;
color: #FFFFFF;
text-align: center;
background-color: #FF0000;
padding: 10px;
margin: 10px auto 0px auto;
width: 200px;
display: block;
overflow: hidden;
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="./style.css">
</head>
<body>
<div class="tst"></div>
<script src="./js_style.js"></script>
</body>
<html>
Now my question is, in which order browser will execute this codes,
like,
1. Browser default
2. External style sheet
3. Internal style sheet (in the head section)
4. Inline style (inside an HTML element)
5. Styles in JavaScript
or in different order? And how can we change the order?
Thanks Everyone.
Upvotes: 0
Views: 17
Reputation: 116100
CSS is not executed. It's just a set of rules that dictates what an element should look like.
So yes, the order you specified is the right order, but that doesn't necessarily mean that a later style overrules an earlier one.
Most important here, is the specificity of the CSS selector. For instance a CSS selector with a class name (like .tst
) is more specific than a selector with a tag name (like div
). So if you would have both selectors, and both of them setting the color of your test div, then the color of .tst
would be used over the other.
But when selectors are of the same specificity, the last one that is encountered is used, so there may be a later one in the same style sheet, or in a different external style sheet. When evaluating this, the order you mentioned is important.
However, that specificity merely affects the internal and external style sheets. When you have inline styles, they always overrule the styles in the style sheet. the same applies to the JavaScript code, since it just changes the inline style of the element.
Upvotes: 1