HTML with CSS

Using CSS with HTML will give you more control to be able to style HTML elements. CSS can be added to HTML in three ways:

  • Inline – Using the style attribute in HTML elements
  • Internal – Using the <style> element in the <head> section
  • External – Using an external CSS file

The best and usually the preferred way to add CSS to HTML, is to put CSS syntax in separate CSS files. However, to simplify the examples, this tutorial will introduce CSS using the style attribute.

Inline Styles

An inline style can be used if a unique style is to be applied to one single occurrence of an element.

To use inline styles, use the style attribute in the relevant tag. The style attribute can contain any CSS property. The example below shows how to change the text color and the left margin of a paragraph:

<p style=“color:blue;margin-left:20px;”>This is a paragraph.</p>

Background Color

The background-color property defines the background color for an element:

<html>

<body style=“background-color:yellow;”>
<h2 style=“background-color:red;”>This is a heading</h2>
<p style=“background-color:green;”>This is a paragraph.</p>
</body>

</html>

Font, Color, and Size

The font-family, color, and font-size properties defines the font, color, and size of the text in an element:

<html>

<body>
<h1 style=“font-family:verdana;”>A heading</h1>
<p style=“font-family:arial;color:red;font-size:20px;”>A paragraph.</p>
</body>

</html>

Text Alignment

The text-align property specifies the horizontal alignment of text in an element:

<html>

<body>
<h1 style=“text-align:center;”>Center-aligned heading</h1>
<p>This is a paragraph.</p>
</body>

</html>

Internal Style Sheet

If one single document has a unique style, an internal style sheet can be used. Internal styles are defined in the <head> section of an HTML page using the <style> tag.

<head>
<style>
body {background-color:yellow;}
p {color:blue;}
</style>
</head>

External Style Sheet

Ideally, you want to use an external style sheet when the style is applied to multiple pages. The look of an entire website can be changed by changing the one externall CSS style sheet file. Each page must be linked to the style sheet using the <link> tag inside the <head> section.

<head>
<link rel=“stylesheet” type=“text/css” href=“mystyle.css”>
</head>