TL;DR — There are three ways to link CSS to HTML, and this tutorial introduces the inline CSS styling method. After reading this article, you will know how to use HTML style attribute in your code. Here is an illustration of all three ways:
Inline CSS: Main Tips
- The inline CSS helps you apply style rules to specific HTML elements.
styleattribute specifies properties and values.
- The inline CSS is limited. For elaborate projects, you should consider other options: internal and external methods.
Introduction to Inline CSS
Inline CSS allows you to apply a unique style to one HTML element at a time. You assign CSS to a specific HTML element by using the style attribute with any CSS properties defined within it.
In the following example, you can see how to describe CSS style properties for an HTML <p> element in the same line of code.
We use a
style attribute to assign CSS styling properties. In this particular case, color and value (
blue) apply to the HTML
<p style="color: blue;">This is a paragraph.</p>
Inline styles in CSS could be useful for previewing changes instantly or adding CSS rules to only one or two elements. When you don't have access to your .css file, knowing how inline style CSS works can be convenient.
Tip: use of inline CSS is not a recommendation. Combining CSS and HTML leads to messy code. Additionally, inline styles method is difficult to update.
Theory is great, but we recommend digging deeper!
Comparison of Inline, Internal and External
Another subject is whether the use of the CSS inline style improves website speed performance. Here are the main points when comparing the speed of all three options:
- Inlining of CSS means that the caching of styles does not occur. Therefore, if the lists of inlined CSS rules are lengthy, the browser will have to act on these rules every time users visit another page of a website.
- If the inlined CSS rules are not lengthy, the problem with caching does not matter.
- However, lists of CSS rules usually are long. Therefore, it is better to use external style sheets or internal CSS.
- The best solution to optimize website speed performance is to use CSS inline only for the essential CSS styles in HTML documents.
- You can optimize your website performance by using external stylesheets.
Inline CSS: Useful Tips
- Inline CSS styles will always override style properties determined in internal or external style sheets.
- Inline CSS does not style pseudo-elements and their -classes. For instance, you cannot style the states of a link, only the link.
- Make a note to only apply CSS inline styles for testing purposes during the production stage of your project.