CSS Core Concepts
Selectors
Selectors are the entities on which we define our CSS rules. We can apply CSS rules on any html tag like p, div, img etc. These selectors are pre-defined HTML tags and are known as base selectors. But in addition to these selectors, CSS allows us to define our own custom selectors known as id and class selectors. Using these selectors we have more control over the presentation.
id
id is a custom selector and is a unique identifier to an element. It can be used once per page. We define rules for id selector in CSS by assigning a name to it follow by '#' sign. And to use that id selector in our html tag we reference it by providing an id attribute whose value is equal to the name of the id.
Syntax for declaring id selector:
#id_name { /*define your rules*/ color:#F00; }
To use this selector all we have to do is reference its name using id attibute.
<p id="id_name"> this is my paragraph. </p>
class
class is a custom selector it can be used any number of times on a same page. We define rules for class selector in CSS by assigning a name to it follow by '.' (dot) sign. And to use that class selector in our html tag we reference it by providing a class attribute whose value is equal to the name of the class.
Syntax for declaring class selector:
.class_name { /*define your rules*/ color:#F00; }
To use this selector all we have to do is reference its name using class attibute.
<p class="class_name"> this is my paragraph. </p>
Grouping in CSS
Sometimes situation occurs when we have more than one selectors having exactly same rules. So in such cases instead of declaring same rules for each selector we group them in one line followed by ','
Syntax for grouping selectors having same rules is:
h1, h2, p { color:#00F; font-family:Arial; }
Unit of measurements in CSS
Some basic measurement unit in CSS are pixels, percentage and em.
- pixel - These are the most basic units and are commonly used. It is generally used for declaring margin, padding, heights and widths of an element.
- percentage - These are always in relative to some other value assigned to its parent element. These are very flexible.
- em - These are the most flexible unit and ideal mode of measurement when the end users viewing device and text preferences are not known. It is roughly estimated to be equal to the size of uppercase letter 'M' that's why name em. User can change the size of elements using browser tools.