1. Tag <style>
If your HTML element has too many styles, you can move them into a special element — tag style
. Usually, it's placed within the <head>
tag and looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>CSS Example</title>
<style>
body {
background-color: lightgray;
}
p {
color: blue;
font-size: 16px;
}
</style>
</head>
<body>
<p>This is an example of using styles inside the <style> tag.</p>
</body>
</html>
Now you don’t need to write a long line of styles for the <body>
tag inside its style
attribute. You can just move them to the style
tag. It's super handy.
The same goes for the <p>
tag (paragraph). What's more, the style defined in a <style>
tag inside <head>
applies to all paragraphs in the document, even if there are thousands of them. This happens because the styles in the <style>
tag are defined inside selectors.
5.2 Selectors
Selectors are a way to choose the HTML elements to which CSS properties will be applied. There are different types of selectors:
Tag Selector
Applies style to all
elements of a certain type. You just specify the tag name and curly braces after it.
tagname {
// styles
}
tagname can be anything: body, image, a, p, … anything
Class Selector
You can also attach CSS properties not to a specific tag but just give a group of CSS properties a name. Such a group in CSS is called a class. This style is applied to all elements with a specific class. Classes are assigned using the class
attribute in HTML.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
p.important {
font-weight: bold;
}
</style>
</head>
<body>
<p class="important">This is important text.</p>
<p>This is normal text.</p>
</body>
</html>
In the example above, only the text of the first paragraph, to which the “important” style/class is applied, will be bold. The second paragraph doesn’t have this style.
When describing styles in the <style>
tag, you can define them in 3 ways:
- tagname { …}
- tagname.classname { …}
- .classname { …}
We’ll dive deeper into selectors when we study CSS. For now, I’m telling you about this because you’ll encounter CSS in the HTML examples, and I’ll often move it into the style tag and use selectors to assign styles to specific HTML elements.
GO TO FULL VERSION