Loading…
Everything will be ready in few seconds
- Theory
- Theory
- Comments
Embedded styles and the style attribute
We already know that it is considered good practice to invoke styles using the <link>
tag:
<link rel="stylesheet" href="style.css">
But there is another way to invoke styles: by embedding them directly into a document instead of invoking them through links. Styles can be invoked either inside the <style>
tag, or they can be written out as the value for in the style
attribute of the HTML elements themselves.
The option for invoking styles in the <style>
tag is used most frequently to optimize the page load time. After all, in this case the browser will not have to send additional queries to the server. The <style>
tag is usually placed inside <head>
. For example:
<head>
<style>
CSS code
</style>
</head>
The second option for embedding styles is through the contents of the style
attribute. The properties and values that are assigned in this way will be applied to just a single element:
<div style="width: 50%;"></div>
Usually, using this method is considered to be bad practice because it’s harder to maintain when some styles are in a stylesheet and others are mixed in with the HTML. However, in exceptional cases it is sometimes more convenient to embed styles in a style
attribute than to write out separate CSS rules. For example, when you need to manage styles from the markup itself, it is not necessary to create separate classes. This happens when some style parameters are assigned using third-party programs or by other people, such as, for example, through a Content Management System.
Let’s take a closer look at the example with style="width: 50%;"
. Let’s suppose that you need to be able to control the width using the property width
within a range of 0%
to 100%
in the markup. To do this through CSS, you would have to create 100 classes and assign them as follows:
.width-0 { width: 0% }
.width-1 { width: 1% }
.width-2 { width: 2% }
/* etc… */
It is much more convenient to pinpoint the assignment of a style specifying width in the style
attribute.
Let’s use this method to apply styles to our visual indicator of the progress that we made in learning new skills.
You can access the intermediate version of our website at this link.
- index.html
- style.css
Thanks! We’ll fix everything at once!
The code has changed, click “Refresh” or turn autorun on.
You’ve gone to a different page
Click inside the mini-browser to shift the focus onto this window.
Comments