About Lesson
CSS (Cascading Style Sheets) is a stylesheet language used to describe the presentation and styling of HTML documents. It allows you to control the layout, appearance, and behavior of elements on a web page. Here are some key concepts and examples of using CSS in HTML:
- Internal Stylesheet:
You can include CSS styles directly within the<style>
element in the<head>
section of your HTML document. This approach is suitable for small projects or when you want to apply styles specific to a single HTML file.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Internal Stylesheet Example</title>
<style>
h1 {
color: blue;
font-size: 24px;
}
p {
color: red;
font-size: 16px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
- External Stylesheet:
You can create a separate CSS file with a.css
extension and link it to your HTML document using the<link>
element. This approach allows you to reuse styles across multiple HTML files, promoting consistency and easier maintenance.
In styles.css
file:
h1 {
color: blue;
font-size: 24px;
}
p {
color: red;
font-size: 16px;
}
In HTML document:
<!DOCTYPE html>
<html>
<head>
<title>External Stylesheet Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
- Inline Styles:
You can apply styles directly to individual HTML elements using thestyle
attribute. This approach is useful for making quick and specific style changes, but it can become cumbersome for large-scale styling.
Example:
<p style="color: blue; font-size: 16px;">This is a paragraph with inline styles.</p>
- CSS Selectors:
CSS selectors allow you to target specific HTML elements or groups of elements to apply styles selectively. There are various types of selectors, such as element selectors, class selectors, ID selectors, and more.
Example:
/* Element selector */
p {
color: red;
}
/* Class selector */
.highlight {
background-color: yellow;
}
/* ID selector */
#main-heading {
font-size: 24px;
}
<p>This is a red paragraph.</p>
<p class="highlight">This paragraph has a yellow background.</p>
<h1 id="main-heading">This is a heading with increased font size.</h1>
These are some basic examples of using CSS with HTML. CSS provides a wide range of properties, selectors, and techniques to control the styling and layout of your web pages. With CSS, you can create visually appealing designs, responsive layouts, and interactive elements to enhance the user experience.
Join the conversation