What is CSS?
CSS (Cascading Style Sheets) is a stylesheet language used to control the presentation of web pages. It allows you to style elements like colors, fonts, layouts, and more.
With CSS, you can separate the content of your HTML (structure) from its visual presentation, improving maintainability and reusability.
Key CSS Concepts
1. Selectors
Selectors are used to target HTML elements for styling:
/* Target all paragraphs */
p {
color: blue;
}
/* Target elements by class */
.my-class {
font-size: 20px;
}
/* Target elements by ID */
#my-id {
background-color: yellow;
}
2. Properties and Values
CSS uses properties to define styles, and values to specify the settings:
/* Change the text color */
color: red;
/* Add a border */
border: 2px solid black;
/* Set padding and margin */
padding: 10px;
margin: 20px;
3. Cascading and Specificity
CSS follows rules for how styles are applied when multiple rules affect the same element:
- Inline styles override internal or external CSS.
- Specificity: ID selectors are more specific than class or element selectors.
- Last rule wins: If two rules have the same specificity, the last one applies.
CSS Examples
1. Styling Text
p {
font-family: Arial, sans-serif;
font-size: 16px;
color: #333;
}
This is an example of styled text.
2. Adding Backgrounds
body {
background-color: #f4f4f4;
background-image: url('background.jpg');
background-size: cover;
}
3. Creating Layouts
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
Flexbox makes it easy to center elements both horizontally and vertically.