Formatting with the Style Attribute
Every HTML element has a default style which is used when displaying the element on the web page. For example, a paragraph by default displays black text on a white background. To change the default style of an element, the style attribute is defined within the element tag.
You Try It: Style Attribute
- Let's look at one attribute - color. Click here to open the Try-It Editor and . . . try it!
- Look carefully at the code on the left side of the editor. Notice that the style attribute is within the opening tag and works in both a heading tag and a paragraph tag. Change the color value to display the text in purple or green or any other colors you might want to try.
- The style attribute has this syntax or structure: style="name:value" and is placed within an element tag. Notice that the syntax of the attribute uses a colon, an equal sign, and quotation marks. This syntax is required for the browser to be able to read and format the web page correctly.
Besides color, there are a number of other elements which can be styled using the style attribute. Think about some of the formatting you might do in a word processing document - changing the font, for example, or centering a title on a page. These can be controlled in html using the style attribute. Let's use the Try-It Editor again to do some additional formatting with the style attribute. Click the name of each attribute in this list and experiment with the style attributes:
- Font: try various font names and see what works. Some common web-safe fonts can be found here. What happens if you try a font that isn't recognized?
- Font-size: the sizes are expressed here in percentage of the default size. In word processing, we size fonts in pixels (px) or points (pt), so you're more used to seeing font sizes as 12, 16, or 32, for example. In web documents, though, we'll use the percentages. For more information about why, check out the sidebar.
- Text-align: on a web page, text can be left-aligned, right-aligned or centered. Try adding the text-align element to the paragraph tag on the Try-It Editor - does it work?
- Background-color: in this Try-It Editor the background-color element is styled in the body tag so it affects the entire page. Do you think it will work on the heading and paragraph tags? Try It!
HINT: if you leave the style element for background-color in the body tag, be sure to change the background color in the paragraph and heading tags; otherwise, you won't be able to see if it's working. - String Multiple Style Attributes Together: Often times you will need to apply multiple attributes. You can easily string multiple attributes together and save yourself some time. Example <p style="color: red; font-size: 20px; font-family: Comic Sans MS; background-color: yellow;">This is a paragraph.</p>