fbpx

Selectors and Styling Rules

In CSS, selectors are used to target HTML elements, and styling rules are applied to these elements using property-value pairs. Let’s explore common types of selectors and styling rules in CSS.

1. Selectors:

a. Element Selector:

Targets HTML elements based on their type.

p {
  color: #333;
}

b. Class Selector:

Targets elements with a specific class attribute.

.button {
  background-color: #4CAF50;
  color: white;
}

c. ID Selector:

Targets a specific element with a unique ID.

#header {
  font-size: 24px;
}

d. Descendant Selector:

Targets an element that is a descendant of another specified element.

article p {
  font-style: italic;
}

e. Child Selector:

Targets an element that is a direct child of another specified element.

ul > li {
  list-style-type: square;
}

f. Attribute Selector:

Targets elements based on the presence or value of their attributes.

input[type="text"] {
  border: 1px solid #ccc;
}

2. Styling Rules:

A styling rule consists of a selector and a set of property-value pairs enclosed in curly braces.

/* Selector */
h1 {
  /* Property-Value Pairs */
  color: #3366cc;
  font-size: 24px;
}

Here are some common styling rules:

a. Color:

p {
  color: #ff0000; /* Red */
}

b. Font:

body {
  font-family: 'Arial', sans-serif;
  font-size: 16px;
  font-weight: bold;
}

c. Layout and Box Model:

.container {
  width: 80%;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
}

d. Flexbox:

.container {
  display: flex;
  justify-content: space-between;
}

e. Responsive Design (Media Queries):

@media screen and (max-width: 600px) {
  body {
    font-size: 14px;
  }
}

These examples illustrate how selectors and styling rules work together to apply styles to HTML elements. The flexibility and power of CSS lie in the combination of different selectors and the application of various styling properties, allowing for the creation of diverse and visually appealing designs on the web. As you become familiar with these fundamental concepts, you can leverage more advanced features and techniques to enhance your styling capabilities in web development.