Traditionally, you can add CSS in three ways:
<link rel="stylesheet" href="foo.css">
<style> h1 { ... }
in the <head>
elementstyle="..."
attribute on specific elementsInline CSS has the drawback that I can't use CSS classes, which is something I need to do. Is there a way to define internal CSS (e.g. a <style></style>
fragment in the <body>
element?
This would be much easier for me because I could create a self-contained HTML snippet with a method in my server code. This kind of method is necessary because I don't control the <head>
section. It is owned by a commercial product. I can only insert content inside the <body>
.
Example:
<div>
<style>
.myclass {...}
</style>
<div class="myclass">...</div>
</div>
Related: https://htmx.org/essays/locality-of-behaviour/
I have seen other websites (like https://amazon.com) where they appear to have several style tags inside the <body>
.
There is a huge gap between theory and practice. Many sites use <style>
in the body.
The editors decided against it. But maybe there will be a change in the future: https://github.com/whatwg/html/issues/1605
The CSS id Selector The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.
You can place HTML style tags in <head> or <body> elements. We'd recommend choosing the first option, as that allows you to keep the content and styling information separate. Note: you can also use <link> elements to apply styles kept in external stylesheets.
CSS can be added to HTML documents in 3 ways: Inline - by using the style attribute inside HTML elements. Internal - by using a <style> element in the <head> section.
Inline styles are used to apply the unique style rules to an element by putting the CSS rules directly into the start tag.
Under the premise, you don't care about invalid HTML in relation of <style>
inside <body>
(which is not that uncommon), you can assign unique identifier i.e.:
<style>
.my-class-1 {
color: gold;
}
</style>
<div class="my-class-1">Fragment Content</div>
<style>
.my-class-2 {
color: tomato;
}
</style>
<div class="my-class-2">Fragment Content</div>
<div class="my-fragment-1">
<style>
.my-fragment-1 .my-class {
color: teal;
}
</style>
<div class="my-class">Fragment Content</div>
</div>
<div class="my-fragment-2">
<style>
.my-fragment-2 .my-class {
color: hotpink;
}
</style>
<div class="my-class">Fragment Content</div>
</div>
<style id="my-style-1">
#my-style-1 + div {
color: orangered;
}
</style>
<div>Fragment Content</div>
<style id="my-style-2">
#my-style-2 + div {
color: indigo;
}
</style>
<div>Fragment Content</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With