CSS
CSS
CSS
BEGINNER-TO-ADVANCEd
Author :
Karan Nath
About the Author
Welcome to my e-book on CSS! I’m Karan Nath, a passionate web developer with a deep appreciation for
the art and science of creating engaging, functional, and user-friendly websites. My journey into web
development began few years ago, and since then, I have been dedicated to mastering the intricacies of
web technologies and sharing that knowledge with others.
My Journey
I started my career in web development with a strong foundation in HTML, CSS, and JavaScript. Over the
years, I’ve worked on a variety of projects ranging from small personal websites to large-scale web
applications. My experience has taught me the importance of clean, efficient code and the value of
continuous learning in this ever-evolving field.
Connect with Me
I’m always excited to connect with fellow developers and web enthusiasts. If you have any questions,
feedback, or just want to chat about web development, feel free to reach out to me:
- Email: nathkaran327@gmail.com
- Instagram: _Code_Craze_
- LinkedIn: Karan Nath
Thank you for picking up this e-book. I hope you find it helpful and inspiring on your journey
to mastering CSS. Happy coding!
External Stylesheet
An external stylesheet is a separate CSS file linked to your HTML file using the `<link>` tag in the HTML
`<head>` section.
Example:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
```
In `styles.css`:
```css
h1 {
color: blue;
}
```
Internal Styles
Internal styles are added directly inside the HTML file using the `<style>` tag in the `<head>` section.
Example:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
h1 {
color: green;
}
</style>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
```
The `@import` rule lets you include other CSS files within your CSS file. Place it at the top of your CSS
file.
```css
@import url('reset.css');
@import url('typography.css');
body {
font-family: Arial, sans-serif;
}
```
Inline Styles
Inline styles are added directly to an HTML element using the `style` attribute.
Example:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1 style="color: red;">Hello World</h1>
</body>
</html>
```
You can use JavaScript to change CSS styles by modifying the `style` property of an HTML element.
Example:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1 id="myHeading">Hello World</h1>
<button onclick="changeStyle()">Change Style</button>
<script>
function changeStyle() {
document.getElementById('myHeading').style.color = 'purple';
}
</script>
</body>
</html>
```
You can change the appearance of lists using the `list-style` property in CSS.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
ul {
list-style-type: square;
}
ol {
list-style-type: upper-roman;
}
</style>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
<ol>
<li>First</li>
<li>Second</li>
</ol>
</body>
</html>
```
Property Lists
A CSS rule is made up of a selector and a declaration block. The declaration block contains one or more
property-value pairs. Each property-value pair is written in the format `property: value;` and is separated
by a semicolon.
Example:
```css
selector {
property1: value1;
property2: value2;
}
```
```css
h1 {
color: blue;
font-size: 24px;
}
```
Multiple Selectors
You can apply the same styles to multiple elements by grouping selectors. Separate each selector with a
comma.
Example:
```css
h1, h2, h3 {
color: navy;
font-family: Arial, sans-serif;
}
```
In this example, the styles will be applied to all `<h1>`, `<h2>`, and `<h3>` elements.
A CSS rule consists of a selector and a declaration block. The selector targets the HTML element(s) to
style, and the declaration block contains the styles.
Example:
```css
/* Selector */
p{
/* Declaration Block */
color: green;
font-size: 16px;
}
```
In this example, the `p` selector targets all `<p>` elements, and the declaration block specifies that the
text color should be green and the font size should be 16px.
Single Line
Single-line comments in CSS start with `/*` and end with `*/`. They are used to add notes or explanations
in the CSS code and do not affect the rendering of the page.
Example:
```css
/* This is a single-line comment */
p{
color: red; /* This is another comment */
}
```
Multiple Line
Multiple-line comments, also known as block comments, are used to add comments that span more than
one line. They also start with `/*` and end with `*/`.
Example:
```css
/*
This is a multiple-line comment.
It can span several lines.
*/
h1 {
color: blue;
}
```
These comments help in documenting the CSS code and can be useful for clarifying complex styles or
sections of the stylesheet.
This chapter explains the use of the `<p>` element in HTML to create and format paragraphs. Proper use
of paragraphs enhances the structure and readability of web content, contributing to a better user
experience.
---
This explanation provides a clear and detailed overview of Chapter 4: Paragraphs, including code
examples and best practices.
Basic Selectors
Basic selectors are used to select HTML elements based on their name, class, or ID.
Example:
```css
/* Selects all <p> elements */
p{
color: blue;
}
Attribute Selectors
Attribute selectors target elements based on their attributes and attribute values.
Example:
```css
/* Selects input elements with a type attribute of "text" */
input[type="text"] {
border: 1px solid black;
}
/* Selects anchor elements with a href attribute that starts with "https" */
a[href^="https"] {
color: green;
}
```
Combinators
Combinators define the relationships between selectors to target elements based on their relationship to
other elements.
Example:
```css
/* Selects <p> elements that are direct children of <div> */
div > p {
color: red;
}
Pseudo-classes
Pseudo-classes apply styles to elements based on their state or position in the document.
Example:
```css
/* Selects the first <p> element */
p:first-of-type {
font-weight: bold;
}
The child pseudo-class selects elements that are direct children of a specified element.
Example:
```css
/* Selects <li> elements that are direct children of <ul> */
ul > li {
list-style-type: none;
}
```
```css
/* Selects all elements with class "highlight" */
.highlight {
background-color: yellow;
}
```
Select Element Using Its ID Without the High Specificity of the ID Selector
You can use attribute selectors or class selectors to achieve similar styling without the high specificity of
ID selectors.
Example:
```css
/* Selects elements with an ID of "item" */
[id="item"] {
font-size: 18px;
}
The Selector
Example:
```css
/* Selects all <p> elements except those with class "exclude" */
p:not(.exclude) {
color: blue;
}
```
Example:
```css
/* Selects the last child of its parent */
p:last-child {
margin-bottom: 0;
}
Example:
```css
/* Selects the first link that is visited */
a:visited {
color: purple;
}
The general sibling combinator (`~`) selects elements that are siblings following a specified element.
Example:
```css
/* Selects all <p> elements that follow a <h1> element */
h1 ~ p {
color: gray;
}
```
ID Selectors
ID selectors target elements with a specific ID. IDs should be unique within a page.
Example:
```css
/* Selects the element with ID "header" */
#header {
background-color: lightgray;
}
```
Example:
```css
/* Styles the range input track */
input[type="range"]::-webkit-slider-runnable-track {
background: #ddd;
height: 8px;
}
```
Example:
```css
/* Selects the first child of its parent */
:first-child {
color: blue;
}
Background Color
Example:
```css
/* Sets a background color for all <div> elements */
div {
background-color: lightblue;
}
```
Background Gradients
Example:
```css
/* Creates a linear gradient from blue to green */
div {
background: linear-gradient(to right, blue, green);
}
Background Image
Example:
```css
/* Sets a background image for all <section> elements */
section {
background-image: url('background.jpg');
}
```
Background Shorthand
The `background` shorthand property allows you to set multiple background properties in one line.
Example:
```css
/* Sets background color, image, and position */
div {
background: lightgray url('image.jpg') no-repeat center center;
}
```
Example:
```css
/* Scales the background image to cover the entire element */
div {
background-size: cover;
}
Background Position
Example:
```css
/* Positions the background image at the top-right corner */
div {
background-position: top right;
}
The `background-origin` property defines the positioning area for background images.
Example:
```css
/* Sets the background positioning area to the content box */
div {
background-origin: content-box;
}
```css
/* Sets multiple background images */
div {
background-image: url('image1.jpg'), url('image2.jpg');
background-position: left top, right bottom;
}
```
Background Attachment
The `background-attachment` property specifies whether the background image is fixed or scrolls with
the content.
Example:
```css
/* Fixes the background image in place */
div {
background-attachment: fixed;
}
Background Clip
The `background-clip` property controls the area within which the background is painted.
Example:
```css
/* Clips the background to the border box */
div {
background-clip: border-box;
}
Background Repeat
The `background-repeat` property controls whether and how the background image repeats.
Example:
```css
/* Prevents the background image from repeating */
div {
background-repeat: no-repeat;
}
background-blend-mode Property
The `background-blend-mode` property specifies how background images and colors blend with each
other.
Example:
```css
/* Blends background images and colors using the multiply mode */
div {
background: url('image.jpg');
background-color: rgba(255, 0, 0, 0.5);
background-blend-mode: multiply;
}
```
To set a background color with opacity, you can use RGBA color values.
Example:
```css
/* Sets a background color with 50% opacity */
div {
background-color: rgba(0, 0, 255, 0.5);
}
```
Using Flexbox
Flexbox is a layout model that makes it easy to center elements both horizontally and vertically.
Example:
```css
/* Container with flexbox */
.container {
display: flex;
justify-content: center; /* Horizontal centering */
align-items: center; /* Vertical centering */
height: 100vh; /* Full viewport height */
}
/* Centered item */
.item {
width: 200px;
height: 100px;
}
```
The `transform` property can be used to center elements by translating them to the center of their
container.
Example:
```css
/* Container */
.container {
position: relative;
height: 100vh; /* Full viewport height */
}
/* Centered item */
.item {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 100px;
}
```
To center block-level elements horizontally, you can use `margin: 0 auto;` if the element has a fixed
width.
Example:
```css
/* Centered block element */
.item {
Using `text-align`
To center inline or inline-block elements within a block-level container, use `text-align: center;` on the
container.
Example:
```css
/* Container with centered text */
.container {
text-align: center;
}
Absolute positioning can center an element by using `top` and `left` properties along with `transform`.
Example:
```css
/* Container */
.container {
position: relative;
height: 100vh; /* Full viewport height */
}
/* Centered item */
.item {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 100px;
}
```
Using `calc()`
Example:
```css
/* Container */
.container {
/* Centered item */
.item {
position: absolute;
top: calc(50% - 50px); /* 50% of container height minus half of item's height */
left: calc(50% - 100px); /* 50% of container width minus half of item's width */
width: 200px;
height: 100px;
}
```
Using `line-height`
For vertically centering single-line text, you can match the `line-height` to the height of the container.
Example:
```css
/* Container */
.container {
height: 100px;
line-height: 100px; /* Same as container height */
text-align: center;
}
/* Centered text */
.item {
display: inline-block;
vertical-align: middle;
line-height: normal; /* Reset line-height for text element */
}
```
The `vertical-align` property can be used with inline or inline-block elements to center them vertically
relative to their container.
Example:
```css
/* Container */
.container {
height: 100px;
line-height: 100px; /* Same as container height */
text-align: center;
}
To center an element in relation to another element, position the child element absolutely within the
parent element.
Example:
```css
/* Parent container */
.parent {
position: relative;
height: 300px;
width: 300px;
background-color: lightgray;
}
Example:
```css
/* Parent container */
.parent {
position: relative;
height: 300px;
width: 300px;
background-color: lightgray;
}
/* Ghost element */
.parent::before {
content: "";
display: block;
height: 100%;
width: 100%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Using Flexbox is an effective way to center elements without needing to specify their height or width.
Example:
```css
/* Parent container */
.container {
display: flex;
justify-content: center; /* Horizontal centering */
align-items: center; /* Vertical centering */
height: 100vh; /* Full viewport height */
background-color: lightgray;
}
/* Centered item */
.item {
background-color: blue;
}
```
To center an image vertically inside a container, you can use Flexbox or the `vertical-align` property with
a flex container.
```css
/* Container */
.container {
display: flex;
align-items: center; /* Vertical centering */
height: 300px;
background-color: lightgray;
}
/* Image */
.container img {
max-width: 100%;
}
```
```css
/* Container */
.container {
height: 300px;
line-height: 300px; /* Same as container height */
text-align: center;
}
/* Image */
.container img {
vertical-align: middle;
max-width: 100%;
}
```
For elements with fixed sizes, you can use `margin: auto;` to center them horizontally within a container.
Example:
```css
/* Container */
.container {
width: 500px;
height: 300px;
background-color: lightgray;
position: relative;
}
To center elements with dynamic height, you can use Flexbox or grid layout.
```css
/* Parent container */
.container {
display: flex;
justify-content: center; /* Horizontal centering */
align-items: center; /* Vertical centering */
height: 100vh; /* Full viewport height */
background-color: lightgray;
}
/* Centered item */
.item {
background-color: blue;
padding: 20px;
}
```
The table layout model can be used for centering elements. Set the container to `display: table` and the
item to `display: table-cell`.
Example:
```css
/* Parent container */
.container {
display: table;
width: 100%;
/* Centered item */
.item {
display: table-cell;
vertical-align: middle; /* Vertical centering */
text-align: center; /* Horizontal centering */
background-color: blue;
width: 200px;
height: 100px;
margin: 0 auto;
}
```
The CSS box model describes the rectangular boxes generated for elements in the document tree. Each
box consists of:
Example:
```css
/* Example of the box model */
.box {
width: 200px;
height: 100px;
padding: 20px;
border: 5px solid black;
margin: 30px;
}
```
In this example:
- Content: 200px width and 100px height.
- Padding: 20px on all sides.
- Border: 5px solid black.
- Margin: 30px on all sides.
box-sizing
The `box-sizing` property controls how the total width and height of an element are calculated.
- content-box (default): The width and height apply only to the content area. Padding and border are
added to the total width and height.
- border-box: The width and height include content, padding, and border. Padding and border are
included within the total width and height.
Example:
```css
/* Border-box sizing */
.box {
box-sizing: border-box;
width: 200px;
height: 100px;
padding: 20px;
border: 5px solid black;
}
```
In this example, the total width of the element will be 200px, including padding and border, instead of
adding them to the width.
Margin Collapsing
Margins between adjacent block-level elements can collapse into a single margin. The larger of the two
margins is used, and the smaller margin is ignored.
Example:
```css
/* Collapsing margins example */
.box1 {
margin-bottom: 20px;
}
.box2 {
margin-top: 30px;
}
```
In this example, the space between `.box1` and `.box2` will be 30px, not 50px.
Example:
```css
/* Applying margin to specific sides */
.box {
margin-top: 10px;
margin-right: 20px;
margin-bottom: 30px;
margin-left: 40px;
}
```
The `margin` shorthand property allows you to set all four margins in one line.
Example:
```css
/* Shorthand margin property */
.box {
margin: 10px 20px 30px 40px; /* top right bottom left */
}
```
To center a block-level element horizontally, set its margins to `auto` and give it a fixed width.
Example:
```css
/* Centering a block-level element horizontally */
.box {
width: 300px;
margin: 0 auto;
}
```
Example:
```css
/* Using negative margin */
.box {
margin-left: -20px;
}
```
In this example, the element will be pulled 20px to the left of its normal position.
Padding Shorthand
The `padding` shorthand property sets padding for all four sides of an element.
Example:
```css
/* Padding shorthand property */
.box {
padding: 10px 20px 30px 40px; /* top right bottom left */
}
```
Example:
```css
/* Padding on specific sides */
.box {
padding-top: 10px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 40px;
}
```
```css
/* Individual padding properties */
.box {
padding-top: 10px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 40px;
}
```
border-radius
Example:
```css
/* Rounded corners */
.box {
border-radius: 10px;
}
```
border-style
The `border-style` property sets the style of the border (e.g., solid, dashed, dotted).
Example:
```css
/* Border style */
.box {
border-style: solid;
}
```
Multiple Borders
You can set different styles, widths, and colors for each border side.
Example:
```css
/* Different styles for each border */
.box {
border-top: 5px solid black;
border-right: 5px dashed red;
border-bottom: 5px dotted blue;
border-left: 5px double green;
}
```
border (Shorthands)
The `border` shorthand property sets width, style, and color for all borders.
Example:
```css
/* Border shorthand property */
.box {
border: 2px solid black;
}
```
border-collapse
The `border-collapse` property sets whether table borders are collapsed into a single border or
separated.
```css
/* Collapsed table borders */
table {
border-collapse: collapse;
}
```
border-image
Example:
```css
/* Using an image as a border */
.box {
border-image: url('border-image.png') 30 round;
}
```
Example:
```css
/* Multi-colored border using gradient */
.box {
border: 10px solid transparent;
border-image: linear-gradient(to right, red, yellow, green) 1;
}
```
border-[left|right|top|bottom]
Example:
```css
/* Border for specific sides */
.box {
border-top: 2px solid black;
border-bottom: 2px dashed gray;
}
```
Overview
The `outline` property is used to draw a line around elements outside the border.
Example:
```css
/* Outline property */
.box {
outline: 2px solid red;
}
```
outline-style
The `outline-style` property sets the style of the outline (e.g., solid, dotted).
Example:
```css
/* Outline style */
.box {
outline-style: dotted;
}
```
overflow-wrap
The `overflow-wrap` property controls how text should be wrapped when it exceeds the width of its
container.
Example:
```css
/* Text wrapping */
.box {
overflow-wrap: break-word;
}
```
overflow-x and overflow-y
The `overflow-x` and `overflow-y` properties control how content overflows horizontally and vertically.
Example:
```css
/* Overflow properties */
.box {
overflow-x: auto; /* Horizontal scrolling */
overflow-y: hidden; /* No vertical scrolling */
}
```
overflow: scroll
The `overflow` property set to `scroll` adds scrollbars to an element if its content overflows.
Example:
```css
/* Scrollbars for overflow */
.box {
overflow: scroll;
}
```
overflow: visible
The `overflow` property set to `visible` makes the content overflow the container without clipping it.
Example:
```css
/* Visible overflow */
.box {
overflow: visible;
}
```
Setting the `overflow` property to any value other than `visible` creates a new block formatting context,
which can help contain floats.
Example:
```css
/* Creating a block formatting context */
.container {
overflow: hidden; /* or overflow: auto; */
}
```
Media queries are used to apply CSS rules based on the characteristics of the device, such as its width,
height, or screen resolution.
Basic Example
```css
/* Media query example */
@media (max-width: 600px) {
.box {
background-color: lightblue;
}
}
```
mediatype
Media types define the category of devices the styles are intended for, such as `screen`, `print`, or `all`.
```css
/* Media type example */
@media screen {
.box {
background-color: lightgreen;
}
}
```
```css
/* Retina display query */
@media only screen and (min-device-pixel-ratio: 2) {
.box {
background-color: lightcoral;
}
}
```
Width vs Viewport
Media queries can target specific widths and viewports for more precise control.
```css
/* Targeting width and viewport */
@media (min-width: 600px) and (max-width: 1200px) {
.box {
background-color: lightyellow;
}
}
```
Media queries help create responsive designs by applying different styles at various screen sizes.
```html
<!-- Link tag with media query -->
<link rel="stylesheet" media="screen and (max-width: 600px)" href="small-screen.css">
```
For compatibility with IE8 and earlier, use a JavaScript polyfill like Respond.js.
```html
<!-- Respond.js for IE8 support -->
<!--[if lt IE 9]>
<script src="https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
```
The `float` property is used to position an element to the left or right of its container, allowing text to wrap
around it.
Example:
```css
/* Floating an image */
img {
float: left;
margin-right: 10px;
}
```
clear Property
The `clear` property is used to control the behavior of floating elements, preventing them from wrapping
around other floated elements.
Example:
```css
/* Clear property */
.clearfix {
clear: both;
}
```
Clearfix
The clearfix hack is used to clear floats, ensuring that a container fully encloses its floated children.
Example:
```css
/* Clearfix example */
.clearfix::after {
content: "";
display: table;
clear: both;
}
```
In-line div Using Float
```css
/* Floating div elements */
.div1 {
float: left;
width: 50%;
}
.div2 {
float: right;
width: 50%;
}
```
KARAN NATH - HTML E-BOOK 39
Chapter 15: Typography
The `font` shorthand property sets font-style, font-variant, font-weight, font-size, line-height, and font-
family.
Example:
```css
/* Font shorthand */
.text {
font: italic small-caps bold 16px/1.5 Arial, sans-serif;
}
```
Quotes
Example:
```css
/* Custom quotes */
q{
quotes: "“" "”" "‘" "’";
}
```
Font Size
Example:
```css
/* Font size */
.text {
font-size: 18px;
}
```
Text Direction
Example:
```css
/* Right-to-left text direction */
.text {
direction: rtl;
}
```
Font Stacks
```css
/* Font stack */
.text {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
```
Text Overflow
The `text-overflow` property specifies how overflowed content that is not displayed should be signaled.
Example:
```css
/* Text overflow */
.text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
```
Text Shadow
Example:
```css
/* Text shadow */
.text {
text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.5);
}
```
Text Transform
Example:
```css
/* Text transform */
.text {
text-transform: uppercase;
}
```
Letter Spacing
Example:
```css
/* Letter spacing */
.text {
letter-spacing: 2px;
}
```
KARAN NATH - E-BOOK 41
Text Indent
The `text-indent` property sets the indentation of the first line of text.
Example:
```css
/* Text indent */
.text {
text-indent: 30px;
}
```
Text Decoration
The `text-decoration` property sets the decoration of text, such as underline, overline, or line-through.
Example:
```css
/* Text decoration */
.text {
text-decoration: underline;
}
```
Word Spacing
Example:
```css
/* Word spacing */
.text {
word-spacing: 10px;
}
```
Font Variant
Example:
```css
/* Font variant */
.text {
font-variant: small-caps;
}
```
Example:
```css
/* Centering elements */
.container {
display: flex;
align-items: center; /* Vertical centering */
justify-content: center; /* Horizontal centering */
height: 100vh;
}
```
Flexbox can be used to create a sticky footer that stays at the bottom of the page, regardless of the
content height.
Example:
```css
/* Sticky footer layout */
.container {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.content {
flex: 1;
}
.footer {
background: lightgray;
padding: 10px;
}
```
Flexbox can automatically adjust the size of elements to optimally fit their container.
Example:
```css
/* Flex items fit to container */
.container {
display: flex;
}
.item {
flex: 1; /* All items will have equal width */
}
```
The Holy Grail layout consists of a header, footer, and three columns (left sidebar, main content, right
sidebar). Flexbox makes this layout simple to achieve.
Example:
```css
/* Holy Grail layout */
.container {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.header, .footer {
background: lightgray;
padding: 10px;
}
.main-content {
display: flex;
flex: 1;
}
.sidebar {
width: 200px;
background: lightblue;
padding: 10px;
}
.main {
flex: 1;
background: lightyellow;
padding: 10px;
}
```
Example:
```css
/* Aligned buttons */
.card {
display: flex;
flex-direction: column;
border: 1px solid #ccc;
padding: 10px;
}
.card-content {
flex: 1;
}
.card-actions {
display: flex;
justify-content: flex-end;
}
```
KARAN NATH - E-BOOK 44
Same Height on Nested Containers
Flexbox ensures that nested containers or items have the same height.
Example:
```css
/* Equal height containers */
.container {
display: flex;
}
.item {
flex: 1;
margin: 10px;
background: lightgray;
padding: 10px;
}
```
Selector specificity determines which CSS rule is applied by the browser. It’s calculated based on the
types of selectors used.
Example:
```css
/* Specificity example */
#id {
/* ID selectors have high specificity */
color: blue;
}
.class {
/* Class selectors have medium specificity */
color: green;
}
element {
/* Element selectors have low specificity */
color: red;
}
```
The `#id` selector has the highest specificity, followed by the `.class` selector, and then the `element`
selector.
Example:
```css
/* !important declaration */
p{
color: red !important;
}
```
In this example, all `p` elements will be red, even if other rules have higher specificity.
Cascading
Cascading determines how conflicting styles are resolved. It considers specificity, importance (such as
`!important`), and the order of appearance in the CSS.
Example:
```css
/* Cascading example */
p{
color: red;
}
p{
color: blue; /* This will be applied because it comes later */
}
```
KARAN NATH - E-BOOK 46
More Complex Specificity Example
Example:
```css
/* Complex specificity */
div p {
color: green; /* Specificity 0-0-1-1 */
}
#main .content p {
color: orange; /* Specificity 0-1-1-1 */
}
p{
color: purple !important; /* This will override all */
}
```
In this example, the `p` elements within `#main .content` will be orange due to higher specificity, but any
`p` element with `!important` will be purple, regardless of other rules.
currentColor
The `currentColor` keyword uses the current color value of an element for properties like `border-color`
or `text-shadow`.
Example:
```css
/* Using currentColor */
.box {
color: red;
border: 2px solid currentColor; /* Border will also be red */
}
```
Color Keywords
Color keywords are predefined color names, like `red`, `blue`, `green`, etc.
Example:
```css
/* Color keywords */
.box {
color: blue;
}
```
Hexadecimal Value
Hexadecimal color values are used to define colors in hexadecimal format (e.g., `#RRGGBB`).
Example:
```css
/* Hexadecimal color */
.box {
color: #ff5733; /* A shade of orange */
}
```
rgb() Notation
The `rgb()` function defines colors using red, green, and blue values.
Example:
```css
/* RGB color */
.box {
color: rgb(255, 87, 51); /* A shade of orange */
}
```
rgba() Notation
The `rgba()` function defines colors with an additional alpha channel for opacity.
```css
/* RGBA color with opacity */
.box {
color: rgba(255, 87, 51, 0.5); /* Semi-transparent orange */
}
```
hsl() Notation
The `hsl()` function defines colors using hue, saturation, and lightness values.
Example:
```css
/* HSL color */
.box {
color: hsl(15, 100%, 60%); /* A shade of orange */
}
```
hsla() Notation
The `hsla()` function defines colors with an additional alpha channel for opacity.
Example:
```css
/* HSLA color with opacity */
.box {
color: hsla(15, 100%, 60%, 0.5); /* Semi-transparent orange */
}
```
Opacity Property
The `opacity` property sets the transparency level of an element. It ranges from `0` (fully transparent) to
`1` (fully opaque).
Example:
```css
/* Opacity property */
.box {
opacity: 0.5; /* 50% transparent */
}
```
For Internet Explorer versions prior to IE9, use the `filter` property to achieve similar opacity effects.
Example:
```css
/* IE compatibility for opacity */
.box {
opacity: 0.5; /* Modern browsers */
filter: alpha(opacity=50); /* IE8 and earlier */
}
```
The `rem` and `em` units are relative to font size and allow for scalable elements.
- `rem` (root em) is relative to the root element's font size (`html`).
- `em` is relative to the font size of the element itself or its parent.
Example:
```css
/* Using rem and em for scalable elements */
html {
font-size: 16px; /* Base font size */
}
.box {
font-size: 1.5rem; /* 24px (16px * 1.5) */
margin: 2em; /* Margin is relative to the element's font size */
}
```
Setting font size with `rem` ensures consistency across elements because it's based on the root
element's font size.
Example:
```css
/* Font size with rem */
.box {
font-size: 1.2rem; /* Font size relative to the root element */
}
```
Example:
```css
/* Using vmin and vmax */
.box {
width: 50vmin; /* 50% of the smaller viewport dimension */
height: 50vmax; /* 50% of the larger viewport dimension */
}
```
vh and vw
```css
/* Using vh and vw */
.box {
width: 50vw; /* 50% of the viewport's width */
height: 50vh; /* 50% of the viewport's height */
}
```
Using Percent %
Example:
```css
/* Using percentage */
.box {
width: 50%; /* 50% of the parent element's width */
}
```
Pseudo-Elements
Pseudo-elements are used to style specific parts of an element. Common pseudo-elements include
`::before` and `::after`, which insert content before or after an element’s content.
Example:
```css
/* Pseudo-elements example */
.box::before {
content: "★"; /* Adds a star before the content */
color: gold;
}
.box::after {
content: "★"; /* Adds a star after the content */
color: gold;
}
```
Pseudo-Elements in Lists
Example:
```css
/* Pseudo-elements in lists */
ul li::marker {
color: red; /* Changes the color of the list item marker */
}
ul li::before {
content: "• "; /* Adds a bullet before list items */
color: blue;
}
```
The `z-index` property controls the stacking order of positioned elements. Higher values are placed in
front of lower values.
Example:
```css
/* Overlapping elements */
.box1 {
position: absolute;
z-index: 1; /* Positioned behind .box2 */
background-color: lightblue;
}
.box2 {
position: absolute;
z-index: 2; /* Positioned in front of .box1 */
background-color: lightcoral;
}
```
Absolute Position
The `position: absolute` property positions an element relative to its nearest positioned ancestor (or the
initial containing block if none exists).
Example:
```css
/* Absolute positioning */
.container {
position: relative; /* Container as the reference point */
}
.box {
position: absolute;
top: 10px;
left: 20px;
background-color: lightgreen;
}
```
Fixed Position
The `position: fixed` property positions an element relative to the viewport, staying in place as the page is
scrolled.
Example:
```css
/* Fixed positioning */
.box {
position: fixed;
bottom: 10px;
right: 10px;
background-color: lightyellow;
}
```
KARAN NATH - E-BOOK 54
Relative Position
The `position: relative` property positions an element relative to its normal position. It does not affect the
layout of surrounding elements.
Example:
```css
/* Relative positioning */
.box {
position: relative;
top: 10px;
left: 20px;
background-color: lightpink;
}
```
Static Positioning
The default positioning value is `static`, which places elements in the normal document flow.
Example:
```css
/* Static positioning (default) */
.box {
position: static;
background-color: lightgray;
}
```
The `display` property specifies how an element is displayed in the document layout. Common values
include `block`, `inline`, `flex`, `grid`, and `none`.
Example:
```css
/* Display property examples */
.block-element {
display: block; /* Takes up full width, with a new line before and after */
}
.inline-element {
display: inline; /* Takes up only as much width as needed, no new lines */
}
.flex-container {
display: flex; /* Enables flexbox layout */
}
.grid-container {
display: grid; /* Enables grid layout */
}
.hidden-element {
display: none; /* Hides the element */
}
```
Using `div` elements to create a table-like structure without using actual `<table>` elements.
Example:
```css
/* Table-like layout using divs */
.table {
display: table;
width: 100%;
}
.table-row {
display: table-row;
}
.table-cell {
display: table-cell;
padding: 10px;
border: 1px solid #ddd;
}
```
Basic Example
CSS Grid Layout provides a two-dimensional grid-based layout system, allowing for more complex and
responsive designs. Here’s a basic example of creating a simple grid.
Example:
```css
/* Basic grid layout */
.container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* Creates three equal columns */
gap: 10px; /* Space between grid items */
}
.item {
background-color: lightblue;
padding: 20px;
border: 1px solid #ddd;
}
```
```html
<!-- HTML structure -->
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
</div>
```
In this example:
- The `.container` element is defined as a grid container with three equal-width columns.
- The `gap` property defines the spacing between the grid items.
- Each `.item` is styled with padding, border, and background color.
Table Layout
CSS can be used to style HTML tables, including their layout and appearance.
Example:
```css
/* Basic table layout */
.table {
width: 100%;
border-collapse: collapse; /* Collapses table borders into a single border */
}
.table th {
background-color: #f4f4f4;
}
```
```html
<!-- HTML table structure -->
<table class="table">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
<td>Row 1, Cell 3</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
<td>Row 2, Cell 3</td>
</tr>
</tbody>
</table>
```
Empty Cells
You can control the appearance of empty cells in a table with the `empty-cells` property.
Example:
- `border-collapse` controls whether table borders are collapsed into a single border or separated.
- `border-spacing` sets the distance between the borders of adjacent cells.
Example:
```css
/* Border collapse and spacing */
.table {
border-collapse: separate; /* Borders are separated */
border-spacing: 10px; /* Space between cells */
}
```
```html
<table class="table">
<!-- Table content here -->
</table>
```
Transition Shorthand
The `transition` shorthand property allows you to specify multiple transition properties in one
declaration. It includes properties for duration, timing function, delay, and which properties to transition.
Example:
```css
/* Transition shorthand example */
.box {
transition: background-color 0.5s ease-in-out, transform 0.3s ease;
}
.box:hover {
background-color: lightcoral;
transform: scale(1.1);
}
```
In this example, `background-color` will transition over `0.5s` with an `ease-in-out` timing function, and
`transform` will transition over `0.3s` with an `ease` timing function.
Cubic-bezier
The `cubic-bezier` function allows you to define a custom timing function for transitions, giving you
control over the acceleration curve.
Example:
```css
/* Custom cubic-bezier timing function */
.box {
transition: transform 0.5s cubic-bezier(0.25, 0.1, 0.25, 1);
}
.box:hover {
transform: rotate(45deg);
}
```
In this example, `cubic-bezier(0.25, 0.1, 0.25, 1)` creates a custom easing effect for the transition.
Transition (Longhand)
The longhand properties for `transition` can be set individually: `transition-property`, `transition-
duration`, `transition-timing-function`, and `transition-delay`.
Example:
```css
/* Transition longhand properties */
.box {
transition-property: background-color, transform;
transition-duration: 0.5s, 0.3s;
transition-timing-function: ease-in-out, ease;
transition-delay: 0s, 0s;
}
.box:hover {
background-color: lightcoral;
transform: scale(1.1);
}
```
This longhand approach is equivalent to the shorthand example but allows you to specify each transition
property separately.
CSS animations are created using the `@keyframes` rule to define the stages of the animation. The
`animation` property applies the animation to an element.
Example:
```css
/* Defining keyframes */
@keyframes slideIn {
from {
transform: translateX(-100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
In this example, the `.box` element will slide in from the left and fade in over `1s`.
While `transition` handles simple state changes, `animation` provides more control with multiple stages
and complex effects.
Example:
```css
/* Transition-based animation example */
.box {
transition: transform 0.5s ease;
}
.box:hover {
transform: scale(1.1);
}
```
In this example, hovering over `.box` will scale it up with a smooth transition effect.
Syntax Examples
Example:
.box {
animation-name: rotate;
animation-duration: 2s;
animation-timing-function: linear;
animation-delay: 0s;
animation-iteration-count: infinite;
}
```
In this example, `.box` rotates continuously with a duration of `2s`, a linear timing function, and no delay.
The `will-change` property informs the browser about upcoming changes, allowing it to optimize
performance.
Example:
```css
/* Optimizing animation performance */
.box {
will-change: transform; /* Optimizes for transformations */
animation: rotate 2s linear infinite;
}
```
By using `will-change`, the browser can optimize rendering for the `transform` property, potentially
improving animation performance.
Rotate
The `rotate` function allows you to rotate an element around a specified point.
Example:
```css
/* Rotate transform */
.box {
transform: rotate(45deg); /* Rotates the element 45 degrees clockwise */
}
```
Scale
The `scale` function resizes an element. You can specify different scaling factors for width and height.
Example:
```css
/* Scale transform */
.box {
transform: scale(1.5); /* Scales the element to 150% of its original size */
}
```
```css
/* Scale with different factors */
.box {
transform: scale(2, 0.5); /* Scales width by 200% and height by 50% */
}
```
Skew
Example:
```css
/* Skew transform */
.box {
transform: skew(20deg, 10deg); /* Skews the element 20 degrees on the X-axis and 10 degrees on the
Y-axis */
}
```
Multiple Transforms
You can apply multiple transform functions to an element, separating them with spaces.
Example:
```css
/* Multiple transforms */
.box {
transform: rotate(45deg) scale(1.2) translateX(50px); /* Rotates, scales, and translates the element */
}
```
The `transform-origin` property sets the point around which an element rotates or scales.
Example:
```css
/* Transform origin */
.box {
transform: rotate(45deg);
transform-origin: top left; /* Rotation occurs around the top-left corner */
}
```
```css
/* Custom transform origin */
.box {
transform: rotate(45deg);
transform-origin: 50% 50%; /* Rotation occurs around the center of the element */
}
```
You can create a 3D compass pointer or needle shape using `rotate` and `perspective` properties.
Example:
```css
/* Compass pointer example */
.compass {
width: 100px;
height: 100px;
background: red;
transform-style: preserve-3d;
transform: rotateX(30deg) rotateY(45deg);
}
```
In this example, `rotateX` and `rotateY` are used to tilt the element in 3D space.
Adding 3D text effects involves using `text-shadow` combined with `transform` for depth.
Example:
```css
/* 3D text effect */
.text {
font-size: 40px;
color: navy;
text-shadow: 1px 1px 0 rgba(0,0,0,0.1),
2px 2px 0 rgba(0,0,0,0.2),
3px 3px 0 rgba(0,0,0,0.3),
4px 4px 0 rgba(0,0,0,0.4),
5px 5px 0 rgba(0,0,0,0.5);
}
```
Backface Visibility
The `backface-visibility` property determines whether the back face of a transformed element is visible
when turned away from the viewer.
Example:
```css
/* Backface visibility */
.box {
width: 100px;
height: 100px;
background: lightblue;
transform: rotateY(180deg);
backface-visibility: hidden; /* Hides the back face */
}
```
3D Cube
Example:
```css
/* 3D cube example */
.cube {
width: 100px;
height: 100px;
position: relative;
transform-style: preserve-3d;
transform: rotateX(30deg) rotateY(45deg);
}
.cube div {
position: absolute;
width: 100%;
height: 100%;
background: rgba(255, 255, 255, 0.8);
border: 1px solid #ddd;
}
Blur
The `blur` function applies a Gaussian blur to an element, making it appear out of focus.
Example:
```css
/* Blur filter */
.image {
filter: blur(5px); /* Applies a blur with a 5px radius */
}
```
The `drop-shadow` function adds a shadow effect to an element, similar to `box-shadow`, but it works
with the transparency of the element’s content.
Example:
```css
/* Drop shadow filter */
.image {
filter: drop-shadow(10px 10px 5px rgba(0, 0, 0, 0.5)); /* Adds a shadow with offset and blur */
}
```
Invert Color
The `invert` function inverts the colors of an element, creating a negative effect.
Example:
```css
/* Invert color filter */
.image {
filter: invert(100%); /* Inverts all colors */
}
```
Example:
```css
/* Multiple filters */
.image {
filter: brightness(0.8) contrast(1.2) sepia(0.3); /* Applies brightness, contrast, and sepia effects */
}
```
Each filter function is applied in sequence, allowing for complex visual effects.
Example:
```css
/* Changing cursor type */
.pointer {
cursor: pointer; /* Changes the cursor to a hand icon */
}
.text {
cursor: text; /* Changes the cursor to an I-beam */
}
.wait {
cursor: wait; /* Changes the cursor to a waiting icon */
}
.crosshair {
cursor: crosshair; /* Changes the cursor to a crosshair */
}
```
Pointer-events
The `pointer-events` property specifies under what circumstances (if any) a particular graphic element
can be the target of mouse events.
Example:
```css
/* Pointer events */
.no-click {
pointer-events: none; /* Disables mouse events on the element */
}
.allow-click {
pointer-events: auto; /* Enables mouse events on the element */
}
```
Caret-color
The `caret-color` property sets the color of the insertion caret (the blinking cursor) in an element that
accepts user input.
Example:
```css
/* Caret color */
.input {
caret-color: red; /* Changes the caret color to red */
}
.input-blue {
caret-color: blue; /* Changes the caret color to blue */
}
```
These properties allow for customized and interactive user experiences by controlling how cursors and
pointer events are handled.
Example:
```css
/* Bottom-only drop shadow */
.box {
position: relative;
}
.box::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 10px;
box-shadow: 0 10px 10px -10px rgba(0, 0, 0, 0.5); /* Creates a bottom-only shadow */
}
```
Drop Shadow
The `box-shadow` property adds shadow effects around an element's frame. You can specify horizontal
and vertical offsets, blur radius, spread radius, and color.
Example:
```css
/* Drop shadow */
.box {
box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.5); /* Adds a shadow with offset, blur, and color */
}
```
To create a shadow that appears inside the element, use the `inset` keyword.
Example:
```css
/* Inner drop shadow */
.box {
box-shadow: inset 5px 5px 10px rgba(0, 0, 0, 0.5); /* Creates an inner shadow */
}
```
Multiple Shadows
You can apply multiple shadows to an element by separating them with commas.
Example:
```css
/* Multiple shadows */
.box {
box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3), -2px -2px 5px rgba(0, 0, 0, 0.3); /* Adds multiple shadow
effects */
}
```
The `shape-outside` property allows you to wrap text around a shape. Using the `circle()` function, you
can create a circular text wrap.
Example:
```css
/* Circle shape outside */
.image {
float: left;
shape-outside: circle(50%);
width: 100px;
height: 100px;
clip-path: circle(50%);
}
.text {
width: 70%;
}
```
Shape Margin
The `shape-margin` property adds space between the shape and the text.
Example:
```css
/* Shape margin */
.image {
float: left;
shape-outside: circle(50%);
width: 100px;
height: 100px;
clip-path: circle(50%);
shape-margin: 10px; /* Adds a 10px margin around the shape */
}
```
By adding `shape-margin`, you ensure that the text does not touch the shape directly, creating a better
visual separation.
Bullet Position
The `list-style-position` property sets whether the list marker should appear inside or outside the content
flow.
Example:
```css
/* Bullet position */
ul {
list-style-position: inside; /* Bullets appear inside the list item */
}
ol {
list-style-position: outside; /* Bullets appear outside the list item */
}
```
The `list-style-type` property changes the marker type for a list. You can use `none` to remove bullets or
numbers.
Example:
```css
/* Removing bullets or numbers */
ul {
list-style-type: none; /* Removes bullets */
}
ol {
list-style-type: none; /* Removes numbers */
}
```
You can change the type of bullets or numbering for lists using the `list-style-type` property.
Example:
```css
/* Custom bullets and numbering */
ul {
list-style-type: square; /* Changes bullets to squares */
}
ol {
list-style-type: upper-roman; /* Changes numbers to upper Roman numerals */
}
```
This allows for customization of list markers to fit the design and styling needs of your content.
You can use CSS counters to create custom numbering systems, such as Roman numerals.
Example:
```css
/* Applying Roman numerals */
ol {
counter-reset: section; /* Resets the counter */
}
li {
counter-increment: section; /* Increments the counter */
}
li::before {
content: counter(section, upper-roman) ". "; /* Adds Roman numerals before each list item */
}
```
Example:
```css
/* Numbering each item */
ol {
counter-reset: item; /* Resets the counter */
}
li {
counter-increment: item; /* Increments the counter */
}
li::before {
content: counter(item) ". "; /* Adds the counter value before each list item */
}
```
Example:
```css
/* Multi-level numbering */
ol {
counter-reset: section; /* Resets the section counter */
}
li {
counter-increment: section; /* Increments the section counter */
}
ol ol {
counter-reset: subsection; /* Resets the subsection counter */
}
ol ol li {
counter-increment: subsection; /* Increments the subsection counter */
}
ol ol li::before {
content: counters(section, ".") "." counter(subsection) " "; /* Adds subsection numbering */
}
```
This example shows how to create hierarchical numbering, useful for documents or outlines with
multiple levels.
calc() Function
The `calc()` function allows you to perform calculations to determine CSS property values.
Example:
```css
/* Using calc() */
.container {
width: calc(100% - 50px); /* Subtracts 50px from 100% of the container's width */
margin-top: calc(10px + 2%); /* Adds 10px and 2% of the container's height */
}
```
attr() Function
The `attr()` function retrieves the value of an attribute of the selected element and uses it in the
stylesheet.
Example:
```css
/* Using attr() */
.tooltip::after {
content: attr(data-tooltip); /* Uses the data-tooltip attribute as the content */
}
```
var() Function
The `var()` function retrieves the value of a custom property (CSS variable).
Example:
```css
/* Using var() */
:root {
--main-color: #3498db;
--padding: 10px;
}
.element {
color: var(--main-color); /* Uses the custom property value */
padding: var(--padding); /* Uses the custom property value */
}
```
radial-gradient() Function
The `radial-gradient()` function creates a radial gradient (a gradient that radiates from an origin).
Example:
```css
/* Using radial-gradient() */
.background {
background: radial-gradient(circle, red, yellow, green); /* Creates a circular radial gradient */
}
```
KARAN NATH - E-BOOK 75
linear-gradient() Function
Example:
```css
/* Using linear-gradient() */
.background {
background: linear-gradient(to right, red, yellow, green); /* Creates a linear gradient from left to right */
}
```
These functions allow for more dynamic and flexible CSS, making it easier to create responsive and
adaptable designs.
Variable Color
CSS custom properties, also known as variables, allow you to store values that can be reused throughout
your stylesheet.
Example:
```css
/* Defining and using a variable for color */
:root {
--main-color: #3498db; /* Defining a variable */
}
.element {
color: var(--main-color); /* Using the variable */
background-color: var(--main-color);
}
```
Variable Dimensions
Example:
```css
/* Defining and using a variable for dimensions */
:root {
--main-padding: 10px;
--main-margin: 20px;
}
.container {
padding: var(--main-padding);
margin: var(--main-margin);
}
```
Variable Cascading
Variables can inherit and cascade just like other CSS properties.
Example:
```css
/* Cascading variables */
:root {
--main-color: #3498db;
}
.section {
--main-color: #e74c3c; /* Overriding the variable within this section */
}
.element {
color: var(--main-color); /* Will be #e74c3c if inside .section, otherwise #3498db */
}
```
CSS variables are flexible and can be used in various contexts. However, they need to be defined before
use.
Example:
```css
/* Using variables correctly */
:root {
--main-color: #3498db;
}
.element {
color: var(--main-color); /* Valid */
}
.invalid {
color: var(--undefined-variable, red); /* Fallback to red if the variable is not defined */
}
```
You can use CSS variables within media queries to adapt styles based on different conditions.
Example:
```css
/* Using variables with media queries */
:root {
--main-padding: 10px;
}
.container {
padding: var(--main-padding); /* The padding will change based on the screen width */
}
```
This allows for more dynamic and responsive design adjustments based on various conditions.
Trapezoid
A trapezoid shape can be created using CSS by manipulating the borders of an element.
Example:
```css
/* Trapezoid */
.trapezoid {
width: 100px;
border-bottom: 50px solid blue;
border-left: 25px solid transparent;
border-right: 25px solid transparent;
height: 0;
}
```
Triangles
Triangles can be created by setting only one border side with a color and the other sides as transparent.
Example:
```css
/* Triangle pointing up */
.triangle-up {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
}
Example:
```css
/* Circle */
.circle {
width: 100px;
height: 100px;
background-color: green;
border-radius: 50%;
}
/* Ellipse */
.ellipse {
width: 150px;
height: 100px;
background-color: green;
border-radius: 50%;
}
```
Bursts
Example:
```css
/* Burst */
.burst {
width: 100px;
height: 100px;
background-color: yellow;
clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2%
35%, 39% 35%);
}
```
Square
Example:
```css
/* Square */
.square {
width: 100px;
height: 100px;
background-color: purple;
}
```
Example:
```css
/* Cube */
.cube {
width: 100px;
height: 100px;
background-color: lightblue;
transform: rotateX(45deg) rotateY(45deg);
transform-style: preserve-3d;
position: relative;
}
.cube::before,
.cube::after {
content: '';
position: absolute;
width: 100px;
height: 100px;
background-color: lightblue;
}
.cube::before {
transform: rotateY(90deg) translateX(50%);
}
.cube::after {
transform: rotateX(90deg) translateY(50%);
}
```
Pyramid
Example:
```css
/* Pyramid */
.pyramid {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
transform: rotateX(-30deg) rotateY(45deg);
transform-style: preserve-3d;
}
```
These examples show how to create various shapes using only CSS, without relying on images or
additional HTML elements.
### Considerations
1. **Avoid Overusing HOCs**: While powerful, excessive use of HOCs can lead to complex and hard-to-
maintain component trees. Use them judiciously and consider alternatives like React hooks for simpler
use cases.
2. **Naming Conventions**: Clearly name your HOCs to reflect their purpose (e.g., `withAuth`,
`withLogging`) to make your codebase easier to understand.
Higher-Order Components are a flexible and powerful way to enhance your React components with
additional functionality while keeping your code modular and reusable.
The `column-count` property divides an element's content into a specified number of columns.
Example:
```css
/* Simple column count */
.container {
column-count: 3; /* Divides the content into 3 columns */
}
```
Column Width
The `column-width` property sets the ideal width of columns. The browser will determine how many
columns will fit based on this width.
Example:
```css
/* Column width */
.container {
column-width: 200px; /* Sets the column width to 200px */
}
```
By using `column-count` and `column-width`, you can easily create multi-column layouts that adapt to
different screen sizes and content lengths.
The `columns` shorthand property can be used to set both `column-count` and `column-width` at the
same time.
Example:
```css
/* Create multiple columns */
.container {
columns: 3 200px; /* Creates 3 columns with a minimum width of 200px each */
}
```
Basic Example
Using the `column-count` and `column-width` properties, you can create a flexible, multi-column layout.
Example:
```css
/* Basic example */
.container {
column-count: 3; /* Divides the content into 3 columns */
column-gap: 20px; /* Adds a 20px gap between columns */
}
.container-wide {
column-width: 200px; /* Sets the column width to 200px */
column-gap: 20px; /* Adds a 20px gap between columns */
}
```
The `column-gap` property allows you to set the space between columns, creating a clear separation and
improving readability.
Using the `display: inline-block` property can help in creating a horizontal navigation bar where items are
justified and aligned.
Example:
```css
/* Justified navigation bar */
.navbar {
text-align: center; /* Centers the navigation bar items */
}
.navbar a {
display: inline-block; /* Aligns links horizontally */
padding: 10px 20px; /* Adds space around the links */
text-decoration: none; /* Removes underline from links */
color: black; /* Sets text color */
}
.navbar a:hover {
background-color: #f0f0f0; /* Changes background on hover */
}
```
In this example, `display: inline-block` ensures that the navigation items line up horizontally and are
responsive to padding and margins. Adjustments to `text-align` and `padding` help to center and space
out the navigation items.
Automatic Inheritance
CSS properties are inherited by default unless explicitly overridden. For example, text-related properties
such as `color`, `font-family`, and `font-size` are inherited by child elements.
Example:
```css
/* Automatic inheritance */
.parent {
color: blue; /* Sets text color */
font-family: Arial, sans-serif; /* Sets font family */
}
.child {
/* Inherits color and font-family from .parent */
}
```
In this example, the text color and font family of `.child` will automatically inherit those of `.parent` unless
specified otherwise.
Enforced Inheritance
Example:
```css
/* Enforced inheritance */
.parent {
color: blue;
}
.child {
color: inherit; /* Explicitly inherits color from .parent */
}
```
This ensures that `.child` will always use the `color` property value of its parent element, regardless of
any other styling rules.
A Basic Implementation
CSS image sprites combine multiple images into a single file, which can reduce the number of HTTP
requests for a web page. To use a sprite, you set the background image of an element and position it
using `background-position`.
Example:
```css
/* Basic sprite implementation */
.sprite {
background-image: url('sprites.png'); /* The image containing all the sprites */
width: 50px; /* Width of the sprite */
height: 50px; /* Height of the sprite */
background-repeat: no-repeat; /* Prevents repeating the background image */
}
.icon-home {
background-position: 0 0; /* Position of the home icon within the sprite */
}
.icon-settings {
background-position: -50px 0; /* Position of the settings icon within the sprite */
}
```
In this example, the `background-position` property is used to display the correct portion of the sprite
image for each icon. Adjust the `background-position` values to align the sprite correctly within the
element.
Clipping and masking are techniques used to control the visibility of an element, but they operate
differently:
- **Clipping** restricts the visibility of an element to a specific shape or path. It hides the parts of the
element that fall outside this shape.
- **Masking** allows for more complex shapes and gradients to be used, where the visibility of the
element can be controlled by a mask image or gradient.
A simple mask can be created using the `mask-image` property with a linear gradient.
Example:
```css
/* Mask that fades an image */
.image {
width: 300px;
height: 200px;
background-image: url('image.jpg');
mask-image: linear-gradient(to bottom, rgba(0, 0, 0, 1), rgba(0, 0, 0, 0));
}
```
This CSS applies a gradient mask to an image, creating a fade effect from solid to transparent.
Clipping (Circle)
Example:
```css
/* Clipping with a circle */
.image {
width: 200px;
height: 200px;
background-image: url('image.jpg');
clip-path: circle(50%);
}
```
Clipping (Polygon)
The `clip-path` property can also use polygons to define complex clipping paths.
Example:
```css
/* Clipping with a polygon */
.image {
width: 300px;
height: 200px;
background-image: url('image.jpg');
clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
}
```
Example:
```css
/* Mask with a hole in the middle */
.image {
width: 300px;
height: 200px;
background-image: url('image.jpg');
-webkit-mask-image: radial-gradient(circle, transparent 50px, black 51px);
mask-image: radial-gradient(circle, transparent 50px, black 51px);
}
```
Example:
```css
/* Using an SVG mask for irregular shapes */
.image {
width: 300px;
height: 200px;
background-image: url('image.jpg');
mask-image: url('mask.svg'); /* SVG mask file */
}
```
This example uses an SVG file to define a mask that applies an irregular shape to the image.
Fragmentation in CSS is used to control the way content is divided across different pages when printing.
The `page-break` properties are used to manage how content breaks between pages.
Example:
```css
/* Page break for printing */
@media print {
.page-break {
page-break-before: always; /* Inserts a page break before the element */
}
.no-break {
page-break-inside: avoid; /* Prevents a page break inside the element */
}
.avoid {
page-break-after: avoid; /* Prevents a page break after the element */
}
}
```
In this example:
- `page-break-before: always` ensures that a page break occurs before the element with the class `page-
break`.
- `page-break-inside: avoid` prevents a page break from occurring inside the element with the class `no-
break`.
- `page-break-after: avoid` prevents a page break from occurring immediately after the element with the
class `avoid`.
These properties help control the layout of printed documents by specifying where content should break
or avoid breaking between pages.
The CSS Object Model (CSSOM) allows for dynamic manipulation of CSS styles using JavaScript. You
can modify existing styles or add new ones to the stylesheet using the CSSOM.
Example:
```javascript
// Adding a background-image rule via CSSOM
In this example:
- `document.styleSheets[0]` selects the first stylesheet on the page.
- `insertRule` adds a new CSS rule to the end of the stylesheet. The rule sets a background image for
elements with the class `dynamic-background`.
- The class is then applied to an element to show the background image.
This method allows for real-time changes to CSS properties, making it possible to update styles
dynamically based on user interactions or other conditions.
Feature queries, using the `@supports` rule, enable you to apply CSS rules conditionally based on
whether the browser supports specific CSS features. This allows you to use advanced CSS properties
while maintaining compatibility with older browsers.
Example:
```css
/* Basic @supports usage */
@supports (display: grid) {
.container {
display: grid; /* Apply grid layout if supported */
grid-template-columns: repeat(3, 1fr); /* Define a 3-column grid */
}
}
In this example:
- The `@supports (display: grid)` rule applies the grid layout to `.container` only if the browser supports
CSS Grid.
- The `@supports not (display: grid)` rule provides a fallback using Flexbox if the browser does not
support Grid.
You can chain multiple feature queries to check for a combination of features.
Example:
```css
/* Chaining feature detections */
@supports (display: grid) and (grid-template-columns: repeat(3, 1fr)) {
.container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* Advanced grid layout */
}
}
In this example:
- The first rule applies a more complex grid layout if the browser supports both CSS Grid and the specific
grid template.
- The second rule provides a simpler grid layout if the browser supports Grid but not the specified
template.
Stacking Context
A stacking context is a three-dimensional concept in CSS that controls the layering of elements.
Elements in a stacking context are stacked according to their `z-index` values, relative to their parent
stacking context.
The `z-index` property determines the stacking order of positioned elements (those with `position` set to
`relative`, `absolute`, `fixed`, or `sticky`) within the same stacking context. Elements with a higher `z-
index` value appear in front of those with a lower value.
Example:
```css
/* Creating a stacking context */
.container {
position: relative;
z-index: 1; /* Creates a stacking context with z-index 1 */
}
.overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 10; /* Stacks above other elements with lower z-index */
}
.content {
position: relative;
z-index: 5; /* Stacks above the container but below the overlay */
}
```
In this example:
- `.container` creates a stacking context with `z-index: 1`.
- `.overlay` is positioned absolutely and has a `z-index` of 10, so it appears on top of the `.container` and
`.content`.
- `.content` has a `z-index` of 5, so it appears above `.container` but below `.overlay`.
Understanding stacking contexts is crucial for managing complex layouts where elements overlap and
ensuring the correct layering order.
A Block Formatting Context (BFC) is an isolated rendering area where block-level elements are formatted.
It affects how elements are laid out and how their margins are handled, particularly in relation to floating
elements and margin collapsing.
Creating a new BFC can be useful for managing layout issues. One common way to create a BFC is by
setting the `overflow` property to a value other than `visible`.
Example:
```css
/* Creating a BFC */
.container {
overflow: hidden; /* Creates a new block formatting context */
background-color: #f0f0f0;
padding: 20px;
}
.child {
float: left; /* Floated element inside the BFC */
width: 200px;
height: 100px;
background-color: #c0c0c0;
}
```
In this example:
- The `.container` element creates a new BFC with `overflow: hidden`.
- The `.child` element is floated, but since it is inside a BFC, its margins will not collapse with other
elements outside of the `.container`.
Using `overflow: hidden`, `overflow: auto`, or `overflow: scroll` on an element will establish a new BFC,
helping to contain floats and manage layout issues effectively.
Using `display: table` and `display: table-cell` can help with vertical centering of content.
Example:
```css
/* Centering with display: table */
.container {
display: table; /* Creates a table context */
width: 100%;
height: 100vh; /* Full viewport height */
}
.centered {
display: table-cell; /* Acts like a table cell */
vertical-align: middle; /* Vertically centers content */
text-align: center; /* Horizontally centers text */
}
```
In this example:
- The `.container` acts as a table.
- The `.centered` element acts as a table cell, allowing its content to be centered both vertically and
horizontally.
Flexbox provides an easy way to center content both horizontally and vertically.
Example:
```css
/* Centering with flexbox */
.container {
display: flex;
justify-content: center; /* Horizontally centers content */
align-items: center; /* Vertically centers content */
height: 100vh; /* Full viewport height */
}
.centered {
width: 50%; /* Example width */
height: 50%; /* Example height */
background-color: #c0c0c0;
}
```
In this example:
- The `.container` uses Flexbox to center `.centered` both horizontally and vertically.
Using CSS transforms to center an element involves setting its position to `absolute` or `fixed` and using
`transform` to adjust its position.
```css
/* Centering with transform */
.container {
position: relative;
height: 100vh; /* Full viewport height */
}
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* Moves the element back to center */
}
```
In this example:
- The `.centered` element is moved to the center of the `.container` using `transform: translate(-50%,
-50%)`.
For single-line text, centering can be achieved by matching the `line-height` to the element's height.
Example:
```css
/* Centering text with line height */
.container {
height: 100px; /* Set height */
line-height: 100px; /* Match line-height to height */
text-align: center; /* Horizontally centers text */
}
.centered {
vertical-align: middle; /* Vertically aligns text */
}
```
In this example:
- The `.container`'s `line-height` matches its height, centering the text vertically.
Centering an element using `position: absolute` involves positioning it relative to its nearest positioned
ancestor.
Example:
```css
/* Centering with position: absolute */
.container {
position: relative;
height: 100vh; /* Full viewport height */
}
In this example:
- The `.centered` element is positioned in the center of the `.container` using `position: absolute` and
`transform`.
You can use pseudo-elements to center content, particularly for decorative purposes.
Example:
```css
/* Centering with pseudo-element */
.container {
position: relative;
height: 100vh; /* Full viewport height */
}
.container::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 100px; /* Example width */
height: 100px; /* Example height */
background-color: #c0c0c0;
transform: translate(-50%, -50%); /* Moves the pseudo-element back to center */
}
```
In this example:
- The `::before` pseudo-element is used to create a centered box inside the `.container`.