CSS Basics
CSS (Cascading Style Sheets) is essential for creating visually appealing web pages. In this section, we'll dive into the basics of CSS, including its properties, values, and syntax.
What are CSS Properties?
CSS properties are used to define the styles for HTML elements. They control various visual aspects like color, size, positioning, and more. A property is always followed by a value. For example:
p {
color: blue;
}
In the example above, the color property is applied to the <p> element, setting its text color to blue.
CSS Syntax
CSS follows a simple structure: selector + property: value. Here's the breakdown:
- Selector: The HTML element to which you want to apply styles (e.g., <p>, <div>).
- Property: The style attribute you want to modify (e.g., color, font-size, background-color).
- Value: The value for the property (e.g., blue, 16px, #fff).
CSS Values
Values define how a property is applied. For example:
- Length values: Used for properties like width and height. They can be in px, em, rem, etc.
div {
width: 200px;
}
p {
color: #ff5733;
}
img {
width: 50%;
}
Common CSS Properties
- Color: Defines the color of text or elements. Example:
color: red;
- Font-size: Controls the size of the text. Example:
font-size: 16px;
- Background-color: Sets the background color of elements. Example:
background-color: #f0f0f0;
- Margin & Padding: Controls the space inside and around elements. Example:
margin: 10px;
,padding: 20px;
Best Practices for CSS Basics
- Use meaningful names for classes and IDs: This makes your code easier to understand and maintain.
- Keep styles modular: Break down your CSS into manageable sections, grouping related styles together.
- Use shorthand properties: For example, use
padding: 10px 20px;
instead of setting individual padding values for top, right, bottom, and left.
Example of CSS Basics
Below is an example that demonstrates how to style a <div> element using the basics of CSS:
div {
width: 300px;
height: 200px;
background-color: #4CAF50;
color: white;
text-align: center;
padding: 20px;
border-radius: 8px;
}
This rule will create a <div> with a green background, white text, and centered content with padding.