CSS An Introduction

Cascading style sheets commonly referred to as CSS controls the appearance and design of the website. CSS is used to style, design, and describe the presentation of web documents written in HTML and XML. Using CSS web developers and designers can control the positioning, fonts, size, colors, background, and shaping of elements.

CSS is recommended by the World Wide Web Consortium to style web documents.

Here is a simple and short example to demonstrate the styling of web documents using CSS.

<!DOCTYPE html>
<html>
<head>
   <style>
      div{ background-color: #bf26d9; padding:5px}
      /* comments for header h1 element styling */
      h1{color: #40a944; text-align: center;}

      p{ font-family: verdana;font-size: 20px;}
   </style>
</head>
<body>
   <div>
      <h1>CSS Example</h1>
      <p>This is a paragraph.</p>
   </div>
</body>
</html>

Example Output

Explanation

In the above example, an internal stylesheet is placed within tags, which gives style to elements within tags.

  • First line style div element a background color and padding used for spacing from internally in elements, in this case, element.
  • The second line is used for comments about h1 styling.
  • The third line line gives color and text alignment to the h1 element.
  • Fourth line change font size and font type to p element.

Bad Practice

  • Don’t use the same rule repetitively inline in tags.
  • Avoid using inline styling whenever possible.

Good practice

Combine elements of common styling to avoid repetition, file size, and loading time.

h1, h2, h3 {font-family: sans-serif; padding: 2px;}

Always use shorthand properties where possible e.g. instead of using padding-top, padding-right, padding-bottom, and padding-left separately simply use the following.

.myclass {padding: 4px 5px 6px 8px;}