CSS (Cascading Style Sheets) is a style sheet language used to describe the presentation of a document written in HTML or XML. It controls the layout, design, and visual appearance of web pages, making them more attractive and easier to use.
Key Concepts of CSS:
- Selectors: CSS applies styles to HTML elements via selectors. Examples:
Element Selector(p,h1, etc.): Targets specific HTML tags.Class Selector(.classname): Targets elements with a specific class.ID Selector(#idname): Targets a single element with a specific ID.
2. Properties and Values: CSS styles elements by assigning properties (such as color, font-size, margin, etc.) with specific values.
p {
color: blue;
font-size: 16px;
}
3. Cascading and Inheritance:
- Cascading: When multiple rules apply to an element, the rule with the highest priority is used. Priority is determined by specificity, importance (
!important), and source order. - Inheritance: Some properties (like
colorandfont-family) are inherited from parent elements to child elements, while others (likemarginandpadding) are not.
4. Box Model: Every element is considered as a box, and the box model defines the space it occupies. The box consists of:
Content: The actual text or images.Padding: Space between the content and the border.Border: The edge around the padding (optional).Margin: Space outside the border, separating the element from others.
5. CSS Syntax:
- A CSS rule consists of a selector and a declaration block.
selector {
property: value;
property: value;
}
6. Responsive Design: CSS allows you to create web pages that adapt to different screen sizes using media queries.
@media (max-width: 600px) {
body {
background-color: lightblue;
}
}
Ways to Use CSS:
- Inline CSS: Styles are applied directly to the HTML elements via the
styleattribute.
<h1 style="color: red;">Hello World</h1>
Internal CSS: Styles are placed within the <style> tag in the <head> of the HTML document.
<style>
p {
color: blue;
}
</style>
External CSS: Styles are written in a separate .css file and linked to the HTML document using the <link> tag.
<link rel="stylesheet" href="styles.css">
Tags: Avoid Excessive CSS Selectors, Critical CSS, Cross-Browser Compatibility, Load CSS Asynchronously, Minify CSS, Optimize Images with CSS, Regularly Update CSS, Responsive Design, Use Descriptive Class and ID Names, Use of External CSS