CSS Selectors
CSS selectors are an essential part of styling web pages. They allow you to target specific elements and apply styles to them. By understanding and using CSS selectors effectively, you can create visually appealing and well-designed web pages.
CSS selectors can be based on different criteria such as element names, classes, IDs, attributes, and more. Let's explore some commonly used CSS selectors:
- Element selector: Selects all elements of a specific type.
1p {
2 color: blue;
3}
- Class selector: Selects all elements with a specific class.
1.my-class {
2 font-weight: bold;
3}
- ID selector: Selects a single element with a specific ID.
1#my-id {
2 background-color: yellow;
3}
- Attribute selector: Selects elements with a specific attribute or attribute value.
1input[type="text"] {
2 border: 1px solid gray;
3}
Using combinations of these selectors, you can achieve more specific targeting of elements in your web page. For example, you can select all li
elements within a ul
element with a class of my-list
:
1ul.my-list li {
2 color: red;
3}
By mastering CSS selectors, you can easily customize the styling of individual elements or groups of elements on your web page. It's like having a powerful toolset to apply your creativity and bring your design ideas to life.
Let's put this knowledge into practice with an example. In the code snippet below, we have defined a CSS selector to make all h1
elements have a red text color:
1<!DOCTYPE html>
2<html>
3 <head>
4 <style>
5 h1 {
6 color: red;
7 }
8 </style>
9 </head>
10 <body>
11 <h1>Hello, World!</h1>
12 </body>
13</html>
When you run this code, you will see that the h1
element's text color is changed to red.
Now, let's apply what we have learned to a real-world scenario. Imagine you are working on a website for a basketball team. You want to highlight the player's name with a different background color based on their position. In this case, you can use class selectors to achieve this effect. Here's an example:
1<!DOCTYPE html>
2<html>
3 <head>
4 <style>
5 .guard {
6 background-color: yellow;
7 }
8 .forward {
9 background-color: green;
10 }
11 .center {
12 background-color: blue;
13 }
14 </style>
15 </head>
16 <body>
17 <h1 class="guard">Kobe Bryant</h1>
18 <h1 class="forward">LeBron James</h1>
19 <h1 class="center">Shaquille O'Neal</h1>
20 </body>
21</html>
In this example, the player's names are wrapped in h1
elements with different class names based on their positions. CSS selectors with corresponding styles are used to apply different background colors to each player's name.
With CSS selectors, you have the power to target and style specific elements on your web page. Play around with different selectors and experiment with various styles to create unique and appealing web designs.
xxxxxxxxxx
const firstName = "John";
const lastName = "Doe";
const fullName = `${firstName} ${lastName}`;
console.log(fullName);