A CSS class is a reusable style definition that can be applied to one or more HTML elements. It is defined in a CSS stylesheet (either an external file, internal <style>
tag in the HTML head, or inline in some cases) using a class selector. The class name starts with a dot (.
) in the CSS and can be assigned to an HTML element using the class
attribute. For example:
/* CSS class definition */
.my - class {
color: blue;
font - size: 18px;
}
<!-- Applying the class to an HTML element -->
<p class="my - class">This paragraph uses the my - class style.</p>
Inline styling involves applying CSS directly to an HTML element using the style
attribute. The styles are written as a series of property - value pairs separated by semicolons. Inline styles have the highest specificity, meaning they will override other CSS rules unless !important is used elsewhere.
<p style="color: green; font - size: 20px;">This paragraph has inline styles.</p>
.css
file, define your classes in it, and link it to your HTML file using the <link>
tag in the <head>
section.<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p class="my - class">Text with class style from external sheet.</p>
</body>
</html>
In styles.css
:
.my - class {
background - color: yellow;
}
<style>
tag in the <head>
of your HTML document.<!DOCTYPE html>
<html>
<head>
<style>
.my - internal - class {
text - decoration: underline;
}
</style>
</head>
<body>
<p class="my - internal - class">Text with class style from internal sheet.</p>
</body>
</html>
Simply add the style
attribute to any HTML element and specify the CSS properties and values.
<div style="width: 300px; height: 200px; background - color: orange;">
This div has inline styles.
</div>
.btn {
background - color: #007BFF;
color: white;
padding: 10px 20px;
border: none;
border - radius: 5px;
}
<button class="btn">Click me</button>
<a href="#" class="btn">Link as a button</a>
.red - text
, use .error - message
if the text is for displaying error information.<!DOCTYPE html>
<html>
<body>
<p id="my - para">This is a paragraph.</p>
<button onclick="changeStyle()">Change Style</button>
<script>
function changeStyle() {
document.getElementById('my - para').style.color ='red';
}
</script>
</body>
</html>
.text - center
, .mb - 10
for margin - bottom: 10px) that can be combined to style elements.!important
in inline styles can lead to conflicts and make it difficult to debug and manage your styles.Both CSS classes and inline styling have their place in web development. CSS classes offer reusability, better organization, and easier maintenance, making them the preferred choice for most styling tasks. Inline styling, on the other hand, is useful for quick changes and dynamic styling. By understanding the fundamental concepts, usage methods, common practices, and best practices of these two techniques, you can create more efficient and maintainable web pages.