Inside this Article
Definition of CSS
Cascading Style Sheets (CSS) is a style sheet language that tells web browsers how to render the elements of HTML and XML documents. CSS specifications are maintained by the World Wide Web Consortium (W3C). CSS enables web developers to apply a consistent style to multiple web pages all at once. A CSS rule consists of a selector and a declaration block. The selector points to the HTML element to style, and the declaration block contains one or more style declarations separated by semicolons. Each declaration specifies a property of the element and a value for that property. For example, this CSS rule sets the text color of all <h1> headings to blue: h1 {color: blue;
}
How Does CSS Work?
CSS works in conjunction with HTML or XML to graphically design web pages. While HTML provides the semantic structure and content of a web page, CSS enhances its style and layout. A web browser applies CSS rules to a document to affect how it is displayed. A CSS rule consists of a selector and a declaration block:- The selector points to the HTML element you want to style. It could be an HTML tag like <h1> or <p>, a class name preceded by a dot like .highlight, or an id preceded by a hash like #navbar.
- The declaration block contains one or more declarations separated by semicolons. Each declaration includes a CSS property name and a value, separated by a colon. For example, color: blue; specifies the text color property to be blue.
- The browser loads the HTML (e.g. receives it from the network).
- It converts the HTML into a DOM (Document Object Model). The DOM represents the document in the computer’s memory.
- The browser then fetches most of the resources that are linked to by the HTML document, such as embedded images, videos, and linked CSS.
- The browser parses the fetched CSS, and sorts the different rules by their selector types into different “buckets”, e.g. element, class, ID, and so on. Based on the selectors it finds, it works out which rules should be applied to which nodes in the DOM, and attaches style to them as required.
- The render tree is laid out in the structure it should appear in after the rules have been applied to it.
- The visual display of the page is shown on the screen.
CSS Syntax
CSS has a simple syntax comprised of selectors, properties, and values. The basic syntax is: selector {property: value;
property: value;
}
- A selector identifies which element or elements in the HTML page the CSS rule applies to. Selectors can be tags (like <h1>, <img>), classes (preceded by a .), IDs (preceded by a #), or other attributes.
- A property is an aspect of the selected element that you want to modify, like color, font, width, border, etc. Each property has a set of valid values, depending on which property is being specified.
- A value is what you set the property to, like blue, 16px, 1px solid black, etc.
- A declaration is a single property-value pair, like color: blue;.
- A declaration block is a list of declarations contained within curly braces { }.
- A rule consists of a selector followed by a declaration block.
color: blue;
font-size: 16px;
} You can have multiple declarations in one declaration block, each separated by a semicolon. And a stylesheet usually contains many rules.
Types of CSS Selectors
CSS selectors are used to “find” (or select) the HTML elements you want to style. There are several types of CSS selectors:- Element Selectors: Select elements based on the element name (tag), like p, h1, div.
For example:p {
text-align: center;
color: red;
} - ID Selectors: Select an element based on the value of its id attribute. ID selectors are prefixed with a “#”.
For example:#navbar {
background-color: #f1f1f1;
padding: 20px;
} - Class Selectors: Select elements with a specific class attribute. Class selectors are prefixed with a “.”.
For example:.highlight {
background-color: yellow;
} - Attribute Selectors: Select elements based on the value of a specified attribute.
For example:[type=”text”] {
width: 200px;
padding: 10px;
} - Pseudo-class Selectors: Select elements based on a certain state, like when a user hovers over it.
For example:a:hover {
color: red;
} - Descendant Selectors: Select elements that are descendants of another specified element.
For example:div p {
color: blue;
} - Child Selectors: Select elements that are the direct children of another specified element.
For example:div > p {
border: 1px solid black;
}
CSS Specificity
If there are two or more CSS rules that point to the same element, the selector with the highest specificity value will “win”, and its style declaration will be applied to that HTML element. Specificity is how browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors. It is calculated by assigning each selector type a value and then tallying the total score for each rule. The specificity hierarchy, from highest to lowest, is:- Inline styles (applied directly to an element using the style attribute)
- IDs
- Classes, pseudo-classes, attribute selectors
- Elements, pseudo-elements
color: blue;
} .highlight {
color: yellow;
} #navbar p {
color: green;
} For a <p> element with a class of “highlight” inside a <div> with an ID of “navbar”, the applicable rule is #navbar p { color: green; } because it has the highest specificity. The rule .highlight { color: yellow; } is not applied because its specificity is lower. Understanding and effectively leveraging CSS specificity allows you to create more predictable and maintainable stylesheets.
CSS Box Model
One of the most fundamental concepts in CSS is the box model. Every HTML element is treated as a box by CSS, and the box model is used to determine an element’s size, padding, margins and borders. The CSS box model consists of:- Content: The content area is where text, images, or other media are displayed. It is bounded by the content edge.
- Padding: The padding area extends the content area to include the element’s padding. It is bounded by the padding edge.
- Border: The border area extends the padding area to include the element’s borders. It is bounded by the border edge.
- Margin: The margin area extends the border area to include an empty area used to separate the element from its neighbors. It is bounded by the margin edge.
———–
| Border |
| ——- |
| | Padding |
| | —– |
| | | | |
| | | | |
| | —– |
| ——- |
———– Each part of the box model can be sized using CSS properties:
- width and height set the size of the content area.
- padding sets the size of the padding area.
- border sets the size and style of the border area.
- margin sets the size of the margin area.
width + padding + border = actual visible/rendered width of an element
height + padding + border = actual visible/rendered height of an element This means that when you set the width and height of an element, the padding and border are added to that size to determine the actual rendered size. You can change this behavior using the box-sizing property. If you set box-sizing: border-box;, the padding and border sizes are included within the specified width and height, leading to a more intuitive sizing approach. Understanding and mastering the CSS box model is crucial for creating precise, well-structured layouts on web pages.
CSS Positioning
CSS positioning allows you to take elements out of the normal document flow and make them behave differently, for example by sitting on top of one another or by always remaining in the same place inside the browser viewport. There are several types of positioning that you can use.- Static Positioning: This is the default for every element. An element with position: static; is not positioned in any special way. It is always positioned according to the normal flow of the page.
- Relative Positioning: An element with position: relative; is positioned relative to its normal position. Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position.
- Absolute Positioning: An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However, if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
- Fixed Positioning: An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element.
- Sticky Positioning: An element with position: sticky; is positioned based on the user’s scroll position. A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport – then it “sticks” in place (like position:fixed).
<div class=”relative”>Relative</div>
<div class=”absolute”>Absolute</div>
<div class=”fixed”>Fixed</div>
<div class=”sticky”>Sticky</div> div {
padding: 20px;
font-size: 28px;
} .static {
position: static;
border: 3px solid #73AD21;
} .relative {
position: relative;
left: 30px;
border: 3px solid #73AD21;
} .absolute {
position: absolute;
top: 80px;
right: 0;
border: 3px solid #73AD21;
} .fixed {
position: fixed;
bottom: 0;
right: 0;
border: 3px solid #73AD21;
} .sticky {
position: sticky;
top: 0;
background-color: green;
border: 2px solid #4CAF50;
} Understanding how to position elements using CSS is a key skill for creating complex and flexible layouts on web pages. It allows you to break out of the standard document flow when needed and create more engaging and interactive designs.
Responsive Web Design with CSS
Responsive web design is an approach to web design that makes web pages render well on a variety of devices and window or screen sizes. With the proliferation of smartphones, tablets, and various screen resolutions on PCs, responsive design has become a necessary skill for web developers. CSS plays a crucial role in implementing responsive design. Here are some key CSS concepts and techniques used in responsive design:- Media Queries: Media queries allow you to specify different styles for different media types/devices. They are a popular technique for delivering a tailored style sheet to desktops, laptops, tablets, and mobile phones. Here’s a basic syntax:
@media screen and (max-width: 600px) {
/* CSS rules for screens up to 600px wide */
} - Flexible Grids: Using relative sizing units like percentages or em instead of fixed units like pixels allows your layout to flexibly adapt to different screen sizes.
- Flexible Images: Making images scalable by using CSS’s max-width: 100%; ensures that images never exceed the width of their containing element.
- Flexbox and Grid: CSS Flexbox and Grid are powerful tools for creating flexible, responsive layouts. They make it easier to rearrange elements based on screen size.
- Responsive Typography: Using relative units like em or rem for font sizes enables the text to scale according to the screen size.
<div class=”sidebar”>Sidebar</div>
<div class=”content”>Content</div>
</div> .wrapper {
overflow: auto;
} .sidebar {
float: left;
width: 30%;
} .content {
float: right;
width: 70%;
} @media screen and (max-width: 600px) {
.sidebar, .content {
width: 100%;
float: none;
}
} In this example, on screens up to 600px wide, the sidebar and content divs will stack on top of each other, each taking up 100% of the width. On wider screens, the sidebar will take up 30% of the width and sit to the left of the content. Responsive web design is essential in today’s multi-device world. Mastering CSS’s responsive design features allows you to create websites that provide an optimal viewing and interaction experience across a wide range of devices.