CSS Syntax

CSS Syntax

A CSS is made of style rules that are interpreted by the browser and then applied to the correct elements in your document. A style rule is made of three parts:

  • Selector
    A selector is an HTML tag or style which the CSS will be applied to. It can be either an existing tag such as H1, H2, table, p or div Or it can be a class or ID which you assigned to an element. This can be anything as long as the HTML element has that class or ID and you reference it as the selector. Classes start with . (period) and id’s start with #(hashtag) Ex: .myclass or #myclass We will get into when to you which later.
  • Property
    A property is a type of attribute that you would like to change. For Example: color, border, font-size, alignment, font weight, etc.
  • Value
    Values are given to properties and describe what you want the property to do or look like. For example, color can be be either red or #ff0000 (Hex number)

There are a few simple rules to writing CSS:

  • More than one selector is separated by a ,(comma)
  • The declaration blocks are surrounded by {} (curly braces)
  • Each declaration includes a CSS property name and a value, separated by a : (colon).
  • More than one declaration is seperated by a ; (semicolon)
  • Sometime an !important after a declaration to overwrite anything else that is styling that element. For Example: p {color:red !important;}

So here is an example:

p {
color: red;
text-align: left;
background-color: #ffffff !important;
}
Test It Yourself

 We used all 3 ways to add CSS Here.

  • · we added font-size:48px;  to the <head> section (HTML TAB)
  • · we added font-style: italic; inline to the P element (HTML TAB)
  • · we added a body background and P color, background color & alignment to the CSS page. (CSS TAB)
Change the HTML and/or CSS on the left to see the RESULT on the right

See the Pen Basic CSS by Ollie (@webocafe)on CodePen.

 

  • CSS saves you time – Write it once and then reuse same style sheet in multiple HTML pages. You can define a style for each HTML element and apply it to as many Web pages as you want.
  • Faster Page Loads – If you are not writing an inline style on every HTML element individually, there will be less coding on the page. Just write one CSS rule for an element and apply it to all the occurrences of that element. Less code means faster download times.
  • Easy Maintenance – So to make a global change, you wont need to edit all the pages individually. Just change the style, and all elements with that class will be updated automatically.
  • Responsive Design – CSS allow content to be optimized for more than one type of device. By using the same HTML document, different versions of a website can be presented for handheld devices such as Laptops,  Tablets and cell phones.