CSS Introduction
CSS or 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, colors, fonts, and overall look of a web page. Here’s a basic introduction to CSS with examples:
1. CSS Syntax
CSS consists of selectors and declarations. The basic syntax is:
selector {
property: value;
}
-
Selector
Targets the HTML element you want to style.
-
Property
The aspect of the element you want to change (e.g., color, font-size).
-
Value
The value you want to apply to the property.
2. Adding CSS to HTML
There are three main ways to include CSS in an HTML document:
-
Inline CSS
Directly within an HTML element using the
styleattribute.<p style="color: blue; font-size: 16px;">This is a blue text.</p> -
Internal CSS
Within a
<style>block in the<head>section of the HTML document.<html> <head> <style> p { color: green; font-size: 18px; } </style> </head> <body> <p>This is a green text.</p> </body> </html> -
External CSS
In a separate CSS file linked to the HTML document.
<!-- HTML file --> <html> <head> <link rel="stylesheet" href="styles.css"> </head> <body> <p>This is a styled text.</p> </body> </html>/* styles.css */ p { color: red; font-size: 20px; }
3. Basic CSS Properties
Here are some common properties you can use:
-
Color
Sets the color of the text.
p { color: red; } -
Font Size
Adjusts the size of the text.
p { font-size: 18px; } -
Background Color
Sets the background color of an element.
div { background-color: lightgrey; } -
Margin
Adds space outside the element's border.
p { margin: 20px; } -
Padding
Adds space inside the element's border.
p { padding: 10px; } -
Border
Adds a border around the element.
p { border: 1px solid black; }
4. CSS Selectors
Selectors are patterns used to select the elements you want to style. Here are a few examples:
-
Element Selector
Targets elements by their name.
p { color: blue; } -
Class Selector
Targets elements with a specific class attribute. Prefixed with a
..<p class="important">This is important.</p>.important { font-weight: bold; } -
ID Selector
Targets an element with a specific id attribute. Prefixed with a
#.<p id="unique">This is unique.</p>#unique { color: orange; }
5. Combining Selectors
You can combine selectors to apply styles to more specific elements.
-
Class and Element Selector
.highlighted p { color: yellow; } -
Descendant Selector
div p { color: grey; }
Conclusion
CSS allows you to separate content from design, making it easier to manage and style your web pages. By understanding the basic syntax and properties, you can start creating visually appealing and well-structured web pages.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
