There exist three methods for incorporating a style sheet:
By utilizing an external style sheet, you can alter the appearance of an entire website with just a single file!
Each HTML page should incorporate a reference to the external style sheet file within the <link> element located within the head section.
Example
External styles are specified within the <link> element, situated within the <head> section of an HTML page.
<!DOCTYPE html> |
An external style sheet can be authored using any text editor and should be saved with a .css extension.
The external .css file should exclusively contain CSS code and should not include any HTML tags.
Below is an example of how the “mystyle.css” file appears:
body { |
Note: Ensure there’s no space between the property value (20) and the unit (px): Incorrect (with space): ‘margin-left:20(px):’ Correct (no space): ‘margin-left:20(px):’ |
An internal style sheet can be employed when a single HTML page requires a distinct style.
The internal style is specified within the <style> element, situated within the head section.
Example
Internal styles are specified within the <style> element, which is located within the <head> section of an HTML page.
<!DOCTYPE html> h1 { |
An inline style can be employed to apply a distinctive style to an individual element.
To utilize inline styles, append the style attribute to the respective element. The style attribute can encompass any CSS property.
Example
Inline styles are specified within the “style” attribute of the corresponding element.
<!DOCTYPE html> |
Tip: Use inline styles judiciously as they forfeit many benefits of style sheets by mixing content with presentation |
If certain properties have been designated for the same selector (element) across various style sheets,
the value from the last parsed style sheet will take precedence.
Suppose an external style sheet contains the following style for the <h1> element:
h1 { |
Now, consider that an internal style sheet also contains the following style for the <h1> element:
h1 { color: orange; } |
Example
If the internal style is declared subsequent to linking the external style sheet, the <h1> elements will appear in the color “orange”.
<head> |
Example
Yet, if the internal style is specified prior to linking the external style sheet, the <h1> elements will be displayed in “navy”.
<head> |
When multiple styles are specified for an HTML element, they follow a cascading order of priority as outlined below, with the highest priority given to:
Therefore, an inline style takes precedence over external and internal styles as well as browser defaults.