Styling HTML Elements with the `style` Attribute and CSS: A Beginner's Guide
Learn the basics of styling HTML elements using both inline styles and external CSS. This tutorial explains how to apply CSS properties directly to HTML elements using the `style` attribute and introduces fundamental CSS concepts for enhancing web page design.
Styling HTML Elements with the `style` Attribute and CSS
The HTML `style` Attribute
The HTML `style` attribute allows you to directly apply CSS (Cascading Style Sheets) styles to individual HTML elements. This provides a way to control various visual aspects of your elements such as color, font, size, text alignment, and background color. While it's often more efficient to define styles in a separate CSS stylesheet, inline styles are useful for applying quick and simple styling to individual elements.
The syntax for the style
attribute is:
`style` Attribute Syntax
<element style="property: value;"> ... </element>
For example, <p style="color:blue;">Blue text</p>
sets the text color of the paragraph to blue.
Styling with CSS Properties
This section demonstrates how to apply styles using common CSS properties:
1. `background-color`
Sets the background color of an element.
Example: `background-color`
<p style="background-color:powderblue;">Powder blue background</p>
2. `color`
Sets the text color of an element.
Example: `color`
<p style="color:green;">Green text</p>
3. `font-family`
Specifies the font for an element.
Example: `font-family`
<p style="font-family:Times New Roman;">Times New Roman font</p>
4. `font-size`
Sets the font size. You can use various units (pixels, ems, etc.).
Example: `font-size`
<p style="font-size:16px;">16 pixel font</p>
5. `text-align`
Controls horizontal text alignment (left, center, right).
Example: `text-align`
<p style="text-align:center;">Centered text</p>