HTML Styles
Styles can be added to an HTML document in three different ways mentioned below.
- Inline Styles
- Internal Styles
- External Styles
Inline Styles
Inline styles can be defined on any HTML element using style
attribute, which can include any CSS property.
These styles are used when we want to apply styles to a specific element in the HTML document.
These styles cannot be shared between elements on an HTML document.
<h2 style="background-color: #55034a; color:#94f1b8;">I am using inline styles</h2>
Internal Styles
Internal styles can be defined on an HTML element using <style>
element as shown below.
Internal styles are used when we want to apply styles to a specific HTML document.
Internal styles can be shared between elements on the same HTML document, where styles are defined.
These styles are shared, so they need to be defined in such a way that they apply to correct elements using element
, class
or id
attributes of elements within the <head>
section of the HTML document.
<style>
h3 {
background-color: #7655ec;
color:#f1a5a5;
}
</style>
HTML content
<h3>I am using internal styles</h3>
External Styles
External stylesheets are linked to an HTML document using the element <link>
as shown below.
External styles are used when we want to share the same styles with multiple HTML documents.
External styles can be shared across several HTML documents, to which they are linked, which helps in maintaining common styles across web pages of a website.
Similar to Inline styles, these styles are shared, so they need to be defined in such a way that they apply to correct elements using element
, class
or id
attributes of elements.
<link rel="stylesheet" href="/assets/styles/external-styles.css">
Content of the external stylesheet external-styles.css
is
h4 {
background-color: #e98b8b;
color:#2b16e7;
}
<h4>I am using external styles</h4>
Which one takes precedence?
In case styles are defined using all the above-mentioned ways to an element, then Inline Styles takes precedence over Internal Styles, which takes precedence over External Styles as shown below.
- Inline Styles > Internal Styles > External Styles
Example
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="/assets/styles/external-styles.css">
<style>
h3 {
background-color: #7655ec;
color:#f1a5a5;
}
</style>
</head>
<body>
<h1>HTML Styles</h1>
<h2 style="background-color: #55034a; color:#94f1b8;">I am using inline styles</h2>
<h3>I am using internal styles</h3>
<h4>I am using external styles</h4>
</body>
</html>
Overall
Adding styles to HTML documents make them look better and interesting.