Suppose if we give some properties to all h1 tags using external css and we have to give one more property (not present in css) to only one of the h1 tag with same remaining properties in css.So do I have to write seperate code by giving that tag a id or there is any shorter way?
two classes sounds like the right way to go, even better than generic h1 tag directly, for example:
index.html
<div>
<h1 class="generic-class">generic</h1>
<h1 class="generic-class">generic</h1>
<h1 class="generic-class specific-class">specific</h1>
</div>
style.css
generic-class {
color: red
}
.specific-class {
font-weight: 800
}
This way, all of them are red, and the last one is red and bold too.
Another solution is to add inline css code directly into the style attribute of the element. In the snippet below I show multiple ways of selecting which element you want to edit with various selectors and js functions.
Though you should keep in mind it's better to have only 1 <h1> on a webpage, mostly for SEO purposes.
// Select h1 by query, for example query below selects the first h1
let h1 = document.querySelector('h1:first-of-type');
h1.style.color = "black";
// Select h1 by id
let h1_2 = document.getElementById('h1_to_select');
h1_2.style.color = "blue";
// Select h1 by index
let h1_3 = document.getElementsByTagName('h1')[1];
h1_3.style.color = "green";
h1{
font-size:16px;
font-family:sans-serif;
color:red
}
<h1>This is a h1 title</h1>
<h1>This is a h1 title</h1>
<h1>This is a h1 title</h1>
<h1 id="h1_to_select">This is a h1 title</h1>
<h1>This is a h1 title</h1>
<h1>This is a h1 title</h1>