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:
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.
<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>
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,
class
attribute is used to assign the highlight
and box
classes to a paragraph (<p>
) and a div (<div>
) element, respectively.<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:-