Syntax in CSS Language

Syntax in CSS Language

CSS (Cascading Style Sheets) is a fundamental technology for web development, allowing designers to control the presentation and layout

of web pages. To effectively use CSS, it’s crucial to grasp the syntax, which defines the rules and structure for applying styles to HTML elements. In this post, we’ll explore the syntax in CSS with examples to help you understand how it works.

Selectors

Selectors are used to target HTML elements that you want to style. They are the beginning of a CSS rule. Here are some common selectors:

  1. Element Selector:
   p {
       font-size: 16px;
   }

This rule selects all <p> elements and sets their font size to 16 pixels.

  1. Class Selector:
   .highlight {
       background-color: yellow;
   }

This rule selects elements with the class “highlight” and gives them a yellow background.

  1. ID Selector:
   #header {
       text-align: center;
   }

This rule selects the element with the ID “header” and centers its text.

  1. Attribute Selector:
   input[type="text"] {
       border: 1px solid gray;
   }

This rule selects all <input> elements with the attribute type="text" and gives them a gray border.

Properties and Values

After selecting an element, you specify the properties you want to change and the values you want to apply to those properties. Here are some examples:

.button {
    background-color: #3498db;
    color: #fff;
    padding: 10px 20px;
    border: none;
}

In this example, we’re styling an element with the class “button.” We set its background color to a shade of blue, the text color to white, added padding, and removed the border.

Declarations

Each property-value pair is known as a declaration and is separated by a semicolon. Declarations are enclosed in curly braces to form a CSS rule:

h1 {
    font-size: 24px;
    color: #333;
}

In this rule, we select all <h1> elements and specify the font size and color for them.

Comments

You can add comments in CSS using /* ... */. Comments are not displayed on the webpage and are useful for explaining your code:

/* This is a comment explaining the following style */
p {
    font-weight: bold;
}

The Cascade

The “Cascading” in CSS refers to the way styles are applied. If multiple conflicting styles are defined for an element, the browser follows a set of rules to determine which style takes precedence. Generally, styles defined closer to the element in the HTML hierarchy override styles defined further away.

p {
    color: red;
}

.container p {
    color: blue;
}

In this example, the text inside a <p> element inside a container with the class “container” will be blue, as it’s closer in the hierarchy.


Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading