CSS stands for Cascading Style Sheet and is a way to add style and decoration to a HTML page. CSS was added in HTML 4.0 and allows for text decoration and element positioning as well as many other cool features. In this article, we will discuss the various ways to apply CSS.
Why the Need for CSS?
When HTML was introduced, it wasn’t designed for the elaborate styling and element positioning that we have today. Over the years, more styling options were added, making the HTML messy and complicated. CSS improves on that by separating the styling code from the HTML.
How to Apply CSS
You can apply CSS three different ways: inline CSS, an external style sheet, and an internal style sheet. You can actually use all 3 methods together. If you use more than one method, the styles are combined into one style. This means that if a style for the
tag has styles applied using an external style sheet and an internal style sheet, the styles for the
tags will be combined. Styles properties are combined in the order that they are applied when interpreted with the last one applied over the proceeding one.
Inline CSS
This basically allows you to put the CSS styles right on the element. It is best to avoid using this method if at all possible.
This is text is red.
Internal Style Sheet
The second option is to use document level CSS or referred to an internal style sheet. The CSS styles are grouped under a
External Style Sheet
The third option is to use a separate CSS file. This file is linked to the HTML document using a tag in the tag. The file is a text file with the CSS styles. You can add multiple files using more than one tag. This is the best option. The CSS file can contain all of the styles needed for the entire site. The CSS file is downloaded and cached on the user’s hard drive. This improves the load time of the page.
Applying Properties Using HTML Elements
When using an external or internal style sheet, CSS styles are applied by using the HTML element, class selectors, or ID selectors. HTML elements are ,
,
tag to red, all text enclosed in a
tag will be red. Of course, it can be overridden with inline styles or styles in the tag.
This will be red.
This will also be red.
As you can see, the color red can be applied to both of the HTML elements. Any text in the
tag will be red and any text within the
tags and all of them would be red (unless overridden with another style).
You can have multiple class selectors on one HTML element. This allows you to apply several styles to the HTML element.
This is bold, red text.
Ordering in the class selector does not matter. The styles will be applied in the order they are listed in CSS. So if you have makeBold last and it has a color of grey, the text will be grey. If makeRed is last, it will override the color of makeBold, but the text will still be bold.