CSS Rule Structure

Rules are the heart of the CSS. It consists of various properties, let’s learn those.

html-form
  • Selector : Selector is a pattern used to select and style HTML elements. They target specific elements or groups of elements to apply CSS rule.

  • Property : CSS property define the visual appearance or behavior of an element. Each property controls a specific aspect of the element’s style.

  • Value : Values are assigned to properties and define how the property should be applied to the selected elements. Values can be specific lengths, colors, keywords, or functions.

  • Rule : CSS rule consist of a selector, property, and value declaration. These rule define how selected elements should be styled.


CSS Selector Types

CSS offers various types of selectors to target and style specific HTML elements or groups of elements. Here are some common CSS selector types:

  • Tag or Element Selector : Targets specific HTML elements by their tag names.

p {
  color: blue; /* Styles all <p> elements */
}


  • Class Selector : Targets elements with a specific class attribute.

.highlight {
  background-color: green; /* Styles elements with class="highlight" */
}


  • ID Selector : Targets a single element with a specific ID attribute.

#header {
  font-size: 24px; /* Styles the element with id="header" */
}


  • Universal Selector : Targets all elements on the page.

* {
  margin: 0;
  padding: 0; /* Resets margin and padding for all elements */
}


  • Attribute Selector : Targets elements based on specific attributes or attribute values.

input[type="submit"] {
  background-color: #007bff; /* Styles <input> elements with type="submit" */
}


  • Pseudo-classes and Pseudo-elements : Selectors that define a special state of an element, such as :hover, :focus, :first-child, ::before, ::after, etc.

a:hover {
  text-decoration: underline; /* Styles links on hover */
}

li:first-child {
  font-weight: bold; /* Styles the first <li> within its parent */
}


  • Descendant Selector : Targets elements that are descendants of another specified element.

.container p {
  font-style: italic; /* Styles <p> elements within elements with class="container" */
}


  • Child Selector : Targets elements that are direct children of another specified element.

ul > li {
  font-weight: bold; /* Styles <li> elements that are direct children of <ul> */
}


  • Adjacent Sibling Selector : Targets elements that are immediately preceded by a specified element.

h2 + p {
  margin-top: 10px; /* Styles <p> elements immediately preceded by <h2> */
}