HTML Style Attribute: Inline Styles

In our previous lesson, we discussed CSS Basics. Now, we will talk about the HTML style attribute and inline styles. Inline styles are CSS properties that are inside the HTML tag they affect. We can add inline styles to an HTML tag with the style attribute. This is a quick and easy way to add styles to any HTML element on a webpage.

If that sounds confusing, don’t worry. It should make sense as we continue.

Let’s say you want to specify the width, height, and background color of a DIV element. A DIV is just a container…a box, if you will. DIVs are usually used to group other HTML elements together. That’ll make more sense later on when we get into layouts. But, for now, we’re going to make a DIV look like a little red box. We’ll do that with the HTML style attribute. Look at the example below.

The HTML style Attribute in Action
Code <div style="width: 20px; height: 20px; background-color: red"></div>
Results

Notice the property called background-color? CSS always uses a hyphen to separate words in a property name. We lucked out. All these properties are fairly self-explanatory.

Hmmm….maybe we want to add some space around the box. We can do that with the margin property. Let’s add 10 pixels of space all around the box.

The HTML style Attribute in Action: Part 2
Code <div style="width: 20px; height: 20px; background-color: red; margin: 10px"></div>
Results

Using the style attribute is a quick and easy way to affect a single element. But it’s not so great if you want to affect several elements at the same time with a single set of rules. For example, if I want another DIV to also be a small red box, I’ll have to type in all those properties all over again.

The HTML style Attribute in Action: Part 3
Code <div style="width: 20px; height: 20px; background-color: red; margin: 10px"></div>

<div style="width: 20px; height: 20px; background-color: red; margin: 10px"></div>
Results

And, if I wanted to apply these rules to twenty DIVs, I’d have to do this twenty times. So, as you can see, it gets tedious if you want to apply the same set of rules to several elements. And that’s where stylesheets come in — whether they are internal stylesheets or external stylesheets. But, before we go into all that, we need to learn how to create rules for stylesheets in general. The rules use the same format for both kinds of style sheets. And that’s what my next lesson is all about. So, my next lesson is about Creating Style Rules for Stylesheets.

Now, you might be a few years building your CSS properties vocabulary, but that’s how the HTML style attribute and inline styles work.

This entry was posted in CSS Tutorials. Bookmark the permalink.

Leave a Reply