A CSS rule is a set of instructions used to define the style of elements on a web page. It consists of two main parts:

  1. Selector: Identifies the HTML elements to which the styles will be applied.
  2. Declaration Block: Contains one or more style declarations, each defining a specific property and its value.
selector {
    property: value;
    property: value;
}

Lets create a new css file src/css/styles.css with below content

p {
    color: blue;          /* Changes text color to blue */
    font-size: 16px;      /* Sets the font size to 16 pixels */
    margin: 10px;         /* Adds 10px margin around the paragraph */
}

Next, We need to link this css to our existing src/index.html by adding below html element above </head>

  <link href="css/styles.css" rel="stylesheet"/>

Types of Selectors in CSS


Comments in CSS Rules

CSS rules can include comments to explain the code, making it easier to read and maintain. Comments are written between /* and */.

/* This styles the main heading */
h1 {
    color: navy;
    font-size: 24px;
}

Lets consider we want to present our login form in a better manner. include below under style tag

body {
                font-family: Arial, sans-serif;
                background: #f4f4f4;
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
            }
            .login-container {
                background: #fff;
                padding: 30px 40px;
                border-radius: 8px;
                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            }
            .login-container h2 {
                margin-bottom: 20px;
            }
            .login-container input[type="text"],
            .login-container input[type="password"] {
                width: 100%;
                padding: 10px;
                margin: 8px 0 16px 0;
                border: 1px solid #ccc;
                border-radius: 4px;
            }
            .login-container button {
                width: 100%;
                padding: 10px;
                background: #007bff;
                color: #fff;
                border: none;
                border-radius: 4px;
                cursor: pointer;
            }
            .login-container button:hover {
                background: #0056b3;
            }

Key Points About CSS Rules

  1. Case Sensitivity: Property names and values are case-insensitive (COLOR is the same as color), but custom identifiers like class names and IDs are case-sensitive.
  2. Semicolons: Each declaration must end with a semicolon (;). The last declaration can omit it, but it’s a best practice to include it.
  3. Cascading: CSS rules are applied in a cascading manner, meaning the order and specificity of rules affect which styles are applied.

By mastering CSS rules, you can control and customize the appearance of web pages effectively.


Classes
Quiz
Videos
References
Books