Chapter 2 CSS (define classes in css)
In HTML, you can define classes using Cascading Style Sheets (CSS) to apply specific styling to multiple HTML elements. Here's how you can define classes in CSS within an HTML document:
CSS Class Definition within HTML:
You can define styles within a <style>
tag in the <head>
section of your HTML file or link an external CSS file that contains your class definitions.
Internal Styles (within the HTML file):
<html> <head> <style> /* Define a class named 'highlight' */ .highlight { color: red; font-weight: bold; } /* Define another class named 'box' */ .box { border: 1px solid #000; padding: 10px; } </style> </head> <body> <!-- HTML content with applied classes --> <p class="highlight">This text is styled using the 'highlight' class.</p> <div class="box">This is a box with a border and padding.</div> </body> </html>
Applying Classes to HTML Elements:
You can apply the defined classes by using the class
attribute in HTML elements.
<!-- HTML content with applied classes -->
<p class="highlight">This text is styled using the 'highlight' class.</p>
<div class="box">This is a box with a border and padding.</div>
In this example,
- 1. The
class
attribute is used to assign thehighlight
andbox
classes to a paragraph (<p>
) and a div (<div>
) element, respectively. - 2. The styles defined for the classes in the
<style>
tag or an external CSS file will be applied to the elements with those classes.
This approach allows you to define styles within your HTML file directly, but for better organization and maintainability, it's common to use an external CSS file to define classes and link it to the HTML file using the <link>
tag in the <head>
section.
Result:-