CSS (Cascading Style Sheets) is used to control the presentation, formatting, and layout of HTML elements. CSS allows you to apply styles such as colors, fonts, spacing, and positioning to HTML elements.
CSS can be added to HTML in three ways:
style
attribute.<style>
element in the <head>
section of the HTML document.<head>
section of the HTML document.Inline CSS is used for styling a single element. For example:
<p style="color: blue; font-size: 20px;">This text is blue and 20px in size.</p>
This text is blue and 20px in size.
Internal CSS is placed inside a <style>
element within the <head>
section. For example:
<style>
p {
color: green;
font-size: 18px;
}
</style>
<p>This text is green and 18px in size.</p>
This text is green and 18px in size.
External CSS is placed in a separate .css file, which is linked to the HTML document. For example:
<link rel="stylesheet" href="styles.css">
In styles.css
:
p {
color: red;
font-size: 16px;
}
This text is red and 16px in size.
CSS specificity determines which styles are applied to an element when multiple styles could apply. The order of precedence is:
Specificity is calculated based on the number of IDs, classes, and elements in the selector.
Here are some additional CSS examples:
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
h1 {
color: #333;
text-align: center;
}
.container {
margin: 0 auto;
padding: 20px;
background-color: #fff;
border-radius: 10px;
max-width: 800px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}