The '<link>' element is used in the HTML head section to connect an external stylesheet to the HTML document. It requires the 'href' attribute to specify the path to the stylesheet file, the 'rel' attribute to indicate the relationship (usually "stylesheet" for CSS), and the 'type' attribute to define the MIME type of the linked file.
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
Storing CSS in separate files improves code organization and maintainability. Create a file (e.g., "styles.css") and place your CSS rules there, then link it in your HTML using the '<link>' element.
/* styles.css */
body {
font-family: Arial, sans-serif;
background-color: #f2f2f2;
}
You can also write CSS directly within an HTML file using the '<style>' element within the '<head>' section. This is useful for small-scale styling.
<head>
<style>
h1 {
color: blue;
}
</style>
</head>
Inline styles are added directly to HTML elements using the 'style' attribute. While not recommended for extensive styling, they provide quick one-off styling changes.
<p style="color: green;">This is a green paragraph.</p>
Type selectors target HTML elements by their tag name and apply styling to all instances of that tag.
p {
font-size: 16px;
}
Class selectors target elements with specific class attributes, allowing you to apply the same styling to multiple elements.
.button {
background-color: blue;
color: white;
}
ID selectors target a single element with a specific 'id' attribute.
#header {
font-size: 24px;
}
HTML attributes like 'class' can have multiple values separated by spaces, allowing an element to be associated with multiple styles.
<div class="box red-border"></div>
You can use class and ID selectors together to create more specific styling rules.
#main-content .highlight {
background-color: yellow;
}
You can apply the same styling to multiple selectors by separating them with commas.
h2, h3 {
font-weight: bold;
}
Selectors can be chained together to target specific nested elements.
article p {
margin-left: 20px; }
Specificity determines which CSS rule takes precedence when multiple rules conflict.
/* Specificity: 0,0,0,1 */
p {
color: red;
}
/* Specificity: 0,0,1,0 */
#main-content {
color: blue;
}
/* Specificity: 0,1,0,0 */
.button {
color: green;
}
/* Specificity: 1,0,0,0 */
h1 {
color: orange;
}
The descendant selector targets elements that are descendants of a specified element.
ul li {
list-style: disc;
}