In the world of web development, CSS (Cascading Style Sheets) is a game-changer. CSS makes dull HTML into visually appealing and well-structured web pages. CSS allows you to control the layout, colours, fonts, and overall appearance of your website, just like the stylist of your web page, deciding what your content will wear, and how it will be presented to the world.
One of the most significant advantages of CSS is that it separates the presentation (style) from the content (structure). This separation makes your code cleaner, more organized, and easier to maintain.
CSS Rules: Selectors and Declarations
CSS operates on a simple rule: selectors and declarations.
Selectors: These are used to select HTML elements you want to style. Selectors can be of various types.
Element Selectors: Select elements based on their tag names. For example, p for paragraphs.
Class Selectors: Select elements based on their class attributes. For example, .class for a specific class.
ID Selectors: Select elements based on their ID attributes. For example, #id for a unique ID.
Descendant Selectors: Select elements that are descendants of another element.
Child Selectors: Select elements that are direct children of another element.
Universal Selectors: Select all elements on a page.
Attribute Selectors: Select elements based on their attributes.
Declarations: Declarations are made up of property and value pairs, separated by a colon. They define the styles for the selected elements. For instance, color: blue sets the text color to blue.
Common CSS Properties
CSS offers a wide array of properties to style your elements. Here are some commonly used ones:
color: Defines text color.
font-size: Sets the size of the text.
background-color: Specifies the background color.
width and height: Control element dimensions.
margin and padding: Define space around and inside elements.
border: Creates borders around elements.
display: Specifies how an element is displayed.
float: Controls element positioning.
position: Sets the positioning method.
text-align: Aligns text horizontally.
font-family: Chooses the font for text.
line-height: Adjusts line spacing.
text-transform: Transforms text appearance.
The Box Model
The CSS box model is crucial for understanding how elements are sized and spaced. Each element is treated as a rectangular box with content, padding, borders, and margins. You can control these areas using properties like width, height, border, margin, and padding.
Units in CSS
CSS uses different units for measurement:
Absolute Units: Pixels (px) and Inches (in).
Relative Units: Percentage (%), Em, and Rem.
Viewport Units: vw and vh.
CSS Calculations: Use the calc() function for mathematical operations.