Css
CSS Units
CSS units define the measurements for properties like width, height, margin, padding, font-size, etc. They determine how elements are sized and positioned on a web page.
Types of CSS Units:
- Absolute Units: Fixed and not scalable.
- Examples: px (pixels), cm (centimeters), mm (millimeters), in (inches), pt (points), pc picas).
- Relative Units: Flexible and scalable based on other elements or the viewport.
- Font-relative: em, rem, %.
- Viewport-relative: vw (width), vh (height), vmin, vmax.
Example:1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Units Example</title>
<style>
/* Absolute Units */
.box-px {
width: 100px;
height: 100px;
background-color: lightblue;
}
/* Font-Relative Units */
.box-em {
width: 10em;
height: 5em;
background-color: lightgreen;
font-size: 20px;
}
/* Viewport-Relative Units */
.box-vw {
width: 50vw;
height: 20vh;
background-color: lightcoral;
}
/* Percentage */
.box-percent {
width: 50%;
height: 100px;
background-color: lightgoldenrodyellow;
}
</style>
</head>
<body>
<h1>CSS Units Example</h1>
<div class="box-px">100px x 100px</div>
<div class="box-em">10em x 5em</div>
<div class="box-vw">50vw x 20vh</div>
<div class="box-percent">50% width</div>
</body>
</html>
CSS Specificity
CSS Specificity is the set of rules that determines which CSS rule takes precedence when multiple rules target the same element. It is calculated based on the types of selectors used.
How Specificity Works
Each selector is assigned a weight based on the following rules (in order of priority):
- Inline Styles (Highest Specificity)
- Example: style="color: red;" in HTML.
- Specificity: 1000.
- IDs
- Example: #header { color: blue; }.
- Specificity: 0100.
- Classes, Attributes, and Pseudo-classes
- Example: .button {}, [type="text"] {}, :hover {}.
- Specificity: 0010.
- Elements and Pseudo-elements (Lowest Specificity)
- Example: h1 {}, p {}, ::before {}.
- Specificity: 0001.
Calculating Specificity
Specificity is written as a 4-part value: (a, b, c, d)
- a: Inline styles.
- b: Number of ID selectors.
- c: Number of class, attribute, and pseudo-class selectors.
- d: Number of element and pseudo-element selectors.
Example:1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Specificity</title>
<style>
/* Specificity: (0, 0, 1, 0) */
.text { color: green; }
/* Specificity: (0, 1, 0, 0) */
#important { color: blue; }
/* Specificity: (1, 0, 0, 0) */
</style>
</head>
<body>
<p id="important" class="text" style="color: red;">
This text will be red due to inline style specificity.
</p>
</body>
</html>
CSS !important
The !important rule is used in CSS to override other styles, regardless of specificity. When applied to a property, it ensures that the property always takes precedence over conflicting rules in the style sheet.
Syntax
selector {
property: value !important;
}
Key Characteristics of !important
- Overrides Specificity:
- A rule with !important will override any other rule, even inline styles or higher-specificity selectors.
- Last One Wins:
- If multiple !important rules apply to the same property, the one defined last in the CSS takes precedence.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS !important Example</title>
<style>
/* General rule */
p {
color: blue;
}
/* Higher specificity rule */
#special {
color: green;
}
/* Force red color with !important */
.override {
color: red !important;
}
</style>
</head>
<body>
<p<This text is blue.</p>
<p id="special">This text is green.</p>
<p id="special" class="override">This text is red because of !important.</p>
</body>
</html>
Explanation
- The first <p> element gets its style from the general p { color: blue; } rule.
- The second <p> element has an ID #special, which has higher specificity, so it turns green.
- The third <p> element has both the ID #special and the class .override. The important rule in .override forces the text color to be red, overriding the green color from #special.
CSS Math Functions
CSS Math Functions allow you to perform calculations directly in CSS properties, enabling dynamic and responsive designs. They are particularly useful for layouts, sizes, and positioning.
Available CSS Math Functions
- calc()
- Combines values with mathematical operations like addition, subtraction, multiplication, and division.
- Syntax:
-
property: calc(expression);
- Example:
- min()
- Returns the smallest value from a list of values.
- Syntax:
-
property: min(value1, value2, ...);
- Example:
- max()
- Returns the largest value from a list of values.
- Syntax:
-
property: max(value1, value2, ...);
- Example:
- clamp()
- Returns a value within a defined range, ensuring it stays between a minimum and maximum.
- Syntax:
-
property: clamp(min, preferred, max);
- Example:
- round() (Upcoming feature in modern CSS)
- Rounds a value to the nearest integer or a specified precision.
(Browser support may vary).
width: calc(100% - 50px);
width: min(50vw, 400px);
font-size: max(16px, 2vw);
width: clamp(300px, 50%, 800px);
Example:1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Math Functions</title>
<style>
.box {
margin: 20px auto;
width: calc(100% - 50px); /* Dynamic width */
max-width: clamp(200px, 50%, 600px); /* Responsive width */
height: min(300px, 50vh); /* Bounded by viewport height */
background-color: lightblue;
}
</style>
</head>
<body>
<div class="box">Resize the window to see the effects!</div>
</body>
</html>
Explanation of the Code
- calc(): Adjusts the width dynamically by subtracting 50px from the full width of the container.
- clamp(): Limits the width between 200px and 600px, preferring 50% of the parent size.
- min(): Restricts the height to a maximum of 50vh or 300px, whichever is smaller.
Example:2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Math Functions Example</title>
<style>
.container {
width: calc(100% - 40px); /* Subtracts 40px from the total width */
margin: 20px auto;
border: 2px solid #333;
}
.box {
width: min(400px, 50vw); /* Takes the smaller value */
height: max(200px, 10vh); /* Takes the larger value */
background-color: lightblue;
margin: 20px auto;
text-align: center;
line-height: clamp(30px, 5vh, 60px); /* Adjust line height */
font-size: clamp(16px, 2vw, 24px); /* Font size between 16px and 24px */
}
</style>
</head>
<body>
<div class="container">
<div class="box">
Resize the window to see CSS Math Functions in action!
</div>
</div>
</body>
</html>
CSS Counters
CSS Counters are a way to create and manipulate custom counters in your web pages. They allow developers to add numbers or counters to elements dynamically, such as for creating numbered lists, chapters, or sections.
CSS Properties for Counters
- counter-reset
- Initializes or resets the counter.
- Example: counter-reset: my-counter;
- counter-increment
- Increments the counter's value.
- Example: counter-increment: my-counter;
- content
- Displays the counter in ::before or ::after pseudo-elements.
- Example: content: counter(my-counter);
Example:1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Counters Example</title>
<style>
/* Initialize the counter */
ol {
counter-reset: item; /* Counter named 'item' */
list-style: none; /* Remove default list styling */
padding: 0;
}
/* Increment and display the counter for each list item */
li::before {
counter-increment: item; /* Increment 'item' counter */
content: counter(item) ". "; /* Display the counter value */
font-weight: bold;
color: blue;
}
/* Styling the list items */
li {
margin: 5px 0;
padding: 5px;
background-color: #f0f0f0;
border: 1px solid #ddd;
}
</style>
</head>
<body>
<h1>Numbered List Using CSS Counters</h1>
<ol>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth item</li>
</ol>
</body>
</html>
Example:2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Counters Example</title>
<style>
/* Initialize the counter */
body {
counter-reset: section; /* Counter named 'section' */
}
/* Increment the counter for each section */
h2::before {
counter-increment: section; /* Increment counter for each h2 */
content: "Section " counter(section) ": "; /* Display counter */
font-weight: bold;
color: blue;
}
/* Nested counters for sub-sections */
h3 {
counter-reset: subsection; /* Reset subsection counter */
}
h3::before {
counter-increment: subsection; /* Increment subsection counter */
content: counter(section) "." counter(subsection) " "; /* Display section.subsection */
font-weight: bold;
color: green;
}
</style>
</head>
<body>
<h2>Introduction</h2>
<p>This is the introduction section.</p>
<h2>Features</h2>
<h2>This is the features section.</h2>
<h3>Feature 1</h3>
<p>Details about feature 1.</p>
<h3>Feature 2</h3>
<p>Details about feature 2.</p>
<h2>Conclusion</h2>
<p>This is the conclusion section.</p>
</body>
</html>
Explanation of Code:
- Initialize Counter:
- counter-reset: section; creates a counter named section at the start of the document.
- Each h2 increments the section counter and displays it using content: "Section " counter(section) ": ";.
- Nested Counters:
- A new counter, subsection, is reset for each h3.
- The counter(section) and counter(subsection) display the section and subsection numbers in a nested format (e.g., 2.1, 2.2).
Use Cases for CSS Counters
- Numbered Lists: Automatically number custom lists or headings.
- Table of Contents: Dynamically number sections and subsections.
- Page Numbers: Add page numbering for printed pages.
- Custom Bullet Points: Replace default list bullets with numbers or symbols.
CSS Counters add dynamic numbering and are especially useful for structured documents like reports, manuals, or content-heavy websites.
CSS Website Layout
CSS Header
A CSS header is typically the top section of a webpage that contains elements like logos, navigation menus, titles, or banners. It is styled using CSS to make it visually appealing and functional.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Header Example</title>
<style>
/* Header Styling */
header {
background-color: #4CAF50; /* Green Background */
color: white; /* White Text */
text-align: center;
padding: 20px 10px;
font-size: 24px;
}
/* Navigation Styling */
nav {
display: flex;
justify-content: center;
background-color: #333;
padding: 10px;
}
nav a {
color: white;
margin: 0 15px;
text-decoration: none;
font-size: 18px;
}
nav a:hover {
color: yellow;
}
/* Main Content */
main {
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<!-- Header Section -->
<header>
Welcome to My Website
</header>
<!-- Navigation Menu -->
<nav>
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#services">Services</a>
<a href="#contact">Contact</a>
</nav>
<!-- Main Content -->
<main>
<p>This is the main content area of the page.</p>
</main>
</body>
</html>
Explanation:
- column-count: 3 : Divides the content into 3 equal columns.
- column-gap: 30px : Adds 30px spacing between columns.
- column-rule : Draws a 2px solid green line between columns.
- column-span: all : Makes the heading span across all columns.
CSS Navigations
CSS Navigation is used to create menus, bars, and links that allow users to navigate through a website. Navigation menus can be styled using CSS for horizontal, vertical, dropdown, or sidebar navigation.
Types of CSS Navigation
- Horizontal Navigation
- Vertical Navigation
- Dropdown Navigation
- Sidebar Navigation
Each type can be styled and customized using properties like display, float, position, and flexbox.
- Horizontal Navigation Bar
- Vertical Navigation Bar
- Dropdown Navigation
- Sidebar Navigation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Horizontal Navigation</title>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover {
background-color: #4CAF50;
}
</style>
</head>
<body>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vertical Navigation</title>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 200px;
background-color: #f4f4f4;
}
li a {
display: block;
color: #333;
padding: 10px;
text-decoration: none;
}
li a:hover {
background-color: #ddd;
color: #4CAF50;
}
</style>
</head>
<body>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
<ul>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dropdown Navigation</title>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
background-color: #333;
}
li {
float: left;
}
li a, .dropdown-btn {
display: block;
color: white;
padding: 14px 16px;
text-decoration: none;
}
li a:hover, .dropdown:hover .dropdown-btn {
background-color: #4CAF50;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #f1f1f1;
}
.dropdown:hover .dropdown-content {
display: block;
}
</style>
</head>
<body>
<ul>
<li><a href="#home">Home</a></li>
<li> class="dropdown">
<a href="javascript:void(0)" class="dropdown-btn">Services</a>
<div class="dropdown-content">
<a href="#web">Web Development</a>
<a href="#app">App Development</a>
<a href="#seo">SEO</a>
</div>
</li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
<ul>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sidebar Navigation Example</title>
<style>
/* Sidebar container */
.sidebar {
height: 100%; /* Full-height */
width: 250px; /* Sidebar width */
position: fixed; /* Fix sidebar to the left */
top: 0;
left: 0;
background-color: #111; /* Dark background */
padding-top: 20px;
}
/* Sidebar links */
.sidebar a {
display: block;
padding: 10px 20px;
color: white;
text-decoration: none;
font-size: 18px;
}
/* Hover effect */
.sidebar a:hover {
background-color: #4CAF50; /* Green background */
color: white;
}
/* Main content */
.main-content {
margin-left: 260px; /* Space for sidebar */
padding: 20px;
}
</style>
</head>
<body>
<!-- Sidebar Navigation -->
<div class="sidebar">
<a href="#home">Home</a>
<a href="#services">Services</a>
<a href="#about">About</a>
<a href="#portfolio">Portfolio</a>
<a href="#contact">Contact</a>
</div>
<!-- Main Content -->
<div class="main-content">
<h1>Welcome to My Website</h1>
<p>This is the main content area. The sidebar navigation stays fixed on the left side as you scroll through the page.</p>
</div>
</body>
</html>
CSS Toggle Bar
A Toggle Bar is a navigation menu or sidebar that can be shown or hidden (toggled) when a button or icon is clicked. It is commonly used in responsive designs for mobile-friendly navigation menus. This can be achieved using HTML, CSS, and optionally JavaScript for toggling the visibility.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Toggle Bar Example</title>
<style>
/* General Reset */
body, html {
margin: 0;
padding: 0;
/* font-family: Arial, sans-serif;*/
}
/* Navigation bar */
.navbar {
background-color: #333;
overflow: hidden;
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 20px;
}
/* Logo */
.logo {
color: #fff;
font-size: 20px;
text-decoration: none;
}
/* Toggle button */
.toggle-btn {
font-size: 24px;
color: #fff;
background: none;
border: none;
cursor: pointer;
}
/* Sidebar */
.sidebar {
position: fixed;
top: 0;
left: -250px; /* Initially hidden */
height: 100%;
width: 250px;
background-color: #444;
padding-top: 60px;
transition: left 0.3s ease;
}
/* Sidebar links */
.sidebar a {
display: block;
color: #fff;
padding: 15px 20px;
text-decoration: none;
font-size: 18px;
}
.sidebar a:hover {
background-color: #4CAF50;
}
/* Toggle Sidebar */
.sidebar.open {
left: 0; /* Show sidebar */
}
/* Main content */
.main-content {
padding: 20px;
}
</style>
</head>
<body>
<!-- Navigation Bar -->
<div class="navbar">
<a href="#" class="logo">My Site</a>
<button class="toggle-btn" onclick="toggleSidebar()">☰</button>
</div>
<!-- Sidebar -->
<div class="sidebar" id="sidebar">
<a href="#home">Home</a>
<a href="#services">Services</a>
<a href="#portfolio">Portfolio</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</div>
<!-- Main Content -->
<div class="main-content">
<h1>Welcome to My Site</h1>
<p>This is an example of a toggle bar in HTML, CSS, and JavaScript. Click the ☰ button to open or close the sidebar navigation.</p>
</div>
<!-- JavaScript to Toggle Sidebar -->
<script>
function toggleSidebar() {
const sidebar = document.getElementById('sidebar');
sidebar.classList.toggle('open');
}
</script>
</body>
</html>
Css columns
CSS columns are used to divide content into multiple columns, similar to how text is laid out in newspapers. The CSS Multi-Column Layout module provides properties to control the number, width, and spacing of columns.
Common Properties for CSS Columns
- column-count: Specifies the number of columns.
- column-width: Specifies the ideal width of columns (browser adjusts the number of columns to fit the width).
- column-gap: Specifies the spacing between columns.
- column-rule: Adds a line (rule) between columns.
- column-rule-width, column-rule-style, column-rule-color: Customize the line between columns.
- columns: A shorthand for setting both column-width and column-count.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Columns Example</title>
<style>
.multicolumn {
column-count: 3; /* Divide content into 3 columns */
column-gap: 20px; /* Space between columns */
}
</style>
</head>
<body>
<h1>CSS Columns Example</h1>
<div class="multicolumn">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
</div>
</body>
</html>
Key Points
- Use column-count to control the number of columns explicitly.
- Use column-width to allow the browser to determine the number of columns based on width.
- Add column-rule for visual separation between columns.
- The properties are responsive, and the number of columns can adjust based on the viewport size.
These examples provide a foundation for creating multi-column layouts with CSS.
CSS Footer Bar
Here’s an example of a footer with menu links styled as a horizontal bar, fixed to the bottom of the page, with a height of 200px:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Fixed Footer with Menu Links</title>
<style>
body {
margin: 0;
font-family: Arial, sans-serif;
padding-bottom: 200px; /* Prevents content from overlapping footer */
}
.footer {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
height: 200px;
background-color: #333; /* Dark background */
color: white;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.footer .menu {
list-style: none;
padding: 0;
margin: 0;
display: flex;
gap: 30px; /* Space between menu items */
}
.footer .menu li {
display: inline;
}
.footer .menu a {
text-decoration: none;
color: white;
font-size: 18px;
transition: color 0.3s ease;
}
.footer .menu a:hover {
color: #4CAF50; /* Highlight menu item on hover */
}
.footer p {
margin-top: 20px;
font-size: 14px;
}
</style>
</head>
<body>
<div class="content">
<h1>Welcome to My Website</h1>
<p>Scroll down to see the footer always fixed at the bottom.</p>
</div>
<div class="footer">
<ul class="menu">
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
<p>© 2024 MyWebsite. All Rights Reserved.</p>
</div>
</body>
</html>
Explanation
- Fixed Footer:
- position: fixed; ensures the footer stays at the bottom of the viewport regardless of scrolling.
- bottom: 0; aligns the footer at the very bottom of the page.
- Footer Height:
- The height is explicitly set to 200px.
- Menu Links:
- Displayed in a horizontal bar using flexbox.
- Links have hover effects for interactivity.
- Padding:
- padding-bottom: 200px; is applied to the <body> to prevent content from overlapping the footer.
This creates a visually appealing and functional fixed footer with menu links at the bottom of the page!
CSS Image Gallery Using Flexbox
Here’s an example of how to create a responsive image gallery using CSS Flexbox:
Example:1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Flexbox Image Gallery</title>
<style>
/* Gallery container */
.gallery {
display: flex;
flex-wrap: wrap; /* Allow wrapping to new rows */
gap: 15px; /* Spacing between items */
justify-content: center; /* Center items horizontally */
padding: 10px;
}
/* Gallery items */
.gallery img {
width: 200px; /* Set image width */
height: 150px; /* Set image height */
object-fit: cover; /* Crop to fit */
border-radius: 8px; /* Rounded corners */
transition: transform 0.3s, box-shadow 0.3s;
}
/* Hover effect */
.gallery img:hover {
transform: scale(1.1); /* Slight zoom effect */
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3); /* Add shadow */
}
</style>
</head>
<body>
<h2>Flexbox Image Gallery</h2>
<div class="gallery">
<img src="https://cdn.shopify.com/s/files/1/0302/4551/9492/files/2150797010.jpg?v=1714126223" alt="Image 1">
<img src="https://cdn.shopify.com/s/files/1/0302/4551/9492/files/2150797012.jpg?v=1714126205" alt="Image 2">
<img src="https://cdn.shopify.com/s/files/1/0302/4551/9492/files/2150797010.jpg?v=1714126223" alt="Image 3">
<img src="https://cdn.shopify.com/s/files/1/0302/4551/9492/files/2150797012.jpg?v=1714126205" alt="Image 4">
<img src="https://cdn.shopify.com/s/files/1/0302/4551/9492/files/2150797010.jpg?v=1714126223" alt="Image 5">
<img src="https://cdn.shopify.com/s/files/1/0302/4551/9492/files/2150797012.jpg?v=1714126205" alt="Image 6">
</div>
</body>
</html>
Explanation:
- Flexbox Layout:
- display: flex creates a flexible container for the gallery.
- flex-wrap: wrap allows images to wrap to the next row if the space isn’t enough.
- gap: 15px creates spacing between the images.
- justify-content: center centers the images horizontally.
- Image Styling:
- Fixed dimensions (width and height) ensure a consistent layout.
- object-fit: cover ensures images are cropped proportionally to fit their containers.
- Hover Effect:
- transform: scale(1.1) adds a zoom effect on hover.
- box-shadow creates a shadow to emphasize the image.
- Responsiveness:
- The flex-wrap property ensures the layout adapts to different screen sizes, making it naturally responsive.
This example demonstrates a simple and visually appealing image gallery using Flexbox, with responsive behavior and hover effects.
Example:2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Image Gallery with Bottom Content</title>
<style>
/* Gallery container */
.gallery {
width: 100%; /* Full-width container */
overflow: hidden; /* Clear floats */
}
/* Gallery item */
.gallery-item {
float: left; /* Float items to the left */
width: 30%; /* Each item takes 30% of the row */
margin: 1.66%; /* Spacing between items */
box-sizing: border-box; /* Include padding and border in width */
text-align: center; /* Center-align the text */
border: 2px solid #ddd; /* Border around each item */
border-radius: 8px; /* Rounded corners */
overflow: hidden; /* Contain floated content */
background: #f9f9f9; /* Background color for the item */
}
/* Image styles */
.gallery-item img {
width: 100%; /* Full width of the container */
height: auto; /* Maintain aspect ratio */
display: block; /* Remove inline spacing */
}
/* Content below image */
.gallery-item .content {
padding: 10px; /* Padding for text area */
font-size: 16px; /* Font size for text */
color: #333; /* Text color */
}
/* Hover effect for images */
.gallery-item img:hover {
transform: scale(1.05); /* Zoom effect */
transition: transform 0.3s ease; /* Smooth zoom */
}
/* Clearfix for container */
.gallery::after {
content: "";
display: table;
clear: both;
}
</style>
</head>
<body>
<h1>Image Gallery with Bottom Content<h1>
<div class="gallery">
<!-- Gallery Item 1 -->
<div class="gallery-item">
<img src="https://cdn.shopify.com/s/files/1/0302/4551/9492/files/image-for-gallery_1.png?v=1734066779" alt="Image 1">
<div class="content">Description for Image 1</div>
</div>
<!-- Gallery Item 2 -->
<div class="gallery-item">
<img src="https://cdn.shopify.com/s/files/1/0302/4551/9492/files/image-for-gallery_2.png?v=1734066779" alt="Image 2">
<div class="content">Description for Image 2</div>
</div>
<!-- Gallery Item 3 -->
<div class="gallery-item">
<img src="https://cdn.shopify.com/s/files/1/0302/4551/9492/files/image-for-gallery_1.png?v=1734066779" alt="Image 3">
<div class="content">Description for Image 3</div>
</div>
<!-- Gallery Item 4 -->
<div class="gallery-item">
<img src="https://cdn.shopify.com/s/files/1/0302/4551/9492/files/image-for-gallery_2.png?v=1734066779" alt="Image 4">
<div class="content">Description for Image 4</div>
</div>
<!-- Gallery Item 5 -->
<div class="gallery-item">
<img src="https://cdn.shopify.com/s/files/1/0302/4551/9492/files/image-for-gallery_1.png?v=1734066779" alt="Image 5">
<div class="content">Description for Image 5</div>
</div>
</div>
</body>
</html>
Explanation:
- Float Property:
- Each .gallery-item is floated to the left, creating a grid-like layout.
- Items wrap to the next row when there’s no space available.
- Image and Content Styling:
- Images are set to width: 100% to fit their container.
- The text below each image is wrapped in a .content div, styled for padding, font size, and alignment.
- Hover Effect:
- The transform: scale(1.05) enlarges the image slightly when hovered over, adding a nice interaction effect.
- Clearfix Hack:
- The ::after pseudo-element is used to clear the float and maintain the structure of the gallery.
- Responsiveness:
- Using percentage widths (30%) and margins ensures the layout adapts to different screen sizes.
This layout demonstrates a simple but effective way to pair images with descriptive content in a gallery format using floats.
CSS Attribute Selectors
CSS Attribute Selectors are used to style HTML elements based on their attributes or attribute values. They provide powerful and flexible ways to apply styles conditionally.
Types of CSS Attribute Selectors:
- [attribute]
Selects elements that have the specified attribute.
[type] {
border: 2px solid blue;
}
Example:
- Styles all elements with a type attribute.
- [attribute=value]
Selects elements with the specified attribute and exact value.
[type="text"] {
background-color: lightgray;
}
Example:
- Styles input elements where type="text."
- [attribute~=value]
Selects elements with a specified attribute containing a space-separated list of values, where one of them matches the given value.
[class~="highlight"] {
color: red;
}
Example:
- Targets elements where the class attribute contains highlight in a list like class="box highlight shadow".
- [attribute|=value]
Selects elements with a specified attribute containing a hyphen-separated list of values that start with the given value.
[lang|="en"] {
font-style: italic;
}
Example:
- Targets elements with lang="en" or lang="en-us".
- [attribute^=value]
Selects elements where the attribute value starts with the given value.
[href^="https"] {
color: green;
}
Example:
- Styles links (<a>) that start with https.
- [attribute$=value]
Selects elements where the attribute value ends with the given value.
[src$=".jpg"] {
border: 3px solid orange;
}
Example:
- Styles images (<img>) with a source ending in .jpg.
- [attribute=value]*
Selects elements where the attribute value contains the given value.
[title*="important"] {
font-weight: bold;
}
Example:
- Styles elements with a title containing the word important.
Example:1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS CSS Attribute Selectors</title>
<style>
/* Style elements with 'type' attribute */
[type] {
padding: 5px;
border: 2px solid blue;
}
/* Style elements where 'type' is 'text' */
[type="text"] {
background-color: lightyellow;
}
/* Style elements where 'class' contains 'highlight' */
[class~="highlight"] {
color: red;
font-weight: bold;
}
/* Style links that start with 'https' */
[href^="https"] {
color: green;
text-decoration: none;
}
/* Style images with 'src' ending in '.png' */
[src$=".png"] {
border: 3px dashed orange;
}
</style>
</head>
<body>
<h1>CSS Attribute Selectors<h1>
<!-- Example Elements -->
<input type="text" placeholder="Text input">
<input type="checkbox">
<p class="box highlight">This is highlighted text.</p>
<a href="https://example.com">Secure Link</a>
<a href="http://example.com">Regular Link</a>
<img src="image.png" alt="Example Image">
</body>
</html>
Css Introduction
CSS (Cascading Style Sheets) is a stylesheet language used to describe the appearance and formatting of HTML documents. It controls the layout, colors, fonts, spacing, and positioning of elements on a web page, making it an essential part of modern web design and development.
Key Features of CSS:
Separation of Content and Presentation:
Cascading Nature:
HTML is used for structuring content, while CSS is used for styling and visual presentation. This separation allows for cleaner, more maintainable code.
The "Cascading" part of CSS means that styles can be applied at different levels (e.g., inline, internal, or external) and will be prioritized based on their specificity and importance.
Why Using CSS?
CSS (Cascading Style Sheets) is crucial for web development because it controls the design and layout of web pages, enhancing their appearance and usability.
Key Benefits:
- Separation of Style and Content: Keeps HTML structure clean while managing design separately.
- Consistent Styling: Apply styles across multiple pages using one CSS file.
- Responsive Design: Easily adapt layouts for different screen sizes.
Example:-
body {
background-color: #ffffff;
}
h1 {
color: green;
text-align: center;
}
p {
font-size: 16px;
margin: 15px;
}
CSS Selectors
CSS selectors are patterns that identify and target HTML elements for styling. They enable applying specific styles based on attributes like tag names, classes, IDs, or relationships between elements.
Types
Universal Selector (*)
Element (Tag) Selector
Class Selector (.)
ID Selector (#)
Attribute Selector
- [attr]: Selects elements with the given attribute.
- [attr="value"]: Selects elements with the exact attribute value.
- [attr^="value"]: Selects elements where the attribute starts with the given value.
- [attr*="value"]: Selects elements where the attribute contains the given value.
- [attr$="value"]: Selects elements where the attribute ends with the given value.
Descendant Selector (Space)
Child Selector (>)
Adjacent Sibling Selector (+)
General Sibling Selector (~)
Pseudo-Class Selectors
Pseudo-Element Selectors
Group Selector (,)
The universal selector targets all elements on a web page.
Example:-
* {
margin: 0;
padding: 0;
}
Example: Removes the margin and padding from all elements.
This selector targets all elements of a specific type or tag.
Example:-
p {
color: blue;
}
Example: Styles all <p> elements to have blue text.
Targets elements with a specific class attribute. It is prefixed with a dot (.).
Example:-
.highlight {
background-color: white;
}
Example: Applies a white background to all elements with class="highlight".
Targets a single element with a specific id attribute. Prefixed with a hash (#). Since IDs are unique, this selector applies to one element.
Example:-
#header {
font-size: 24px;
}
Example: Styles the element with id="header" to have a font size of 24px.
Targets elements based on their attributes. You can style elements with specific attributes or values.
Example:-
a[target="_blank"] {
color: red;
}
Example: Styles all links (<a>) with target="_blank" to have red text.
Variations:
input[required] {
border: 2px solid red;
}
input[type="text"] {
background-color: lightyellow;
}
a[href^="https"] {
color: green;
}
a[href*="example"] {
font-weight: bold;
}
img[src$=".jpg"] {
border: 3px solid blue;
}
Selects elements that are descendants of a specified parent element.
Example:-
div p {
color: green;
}
Example: Styles <p> elements inside any <div> with green text.
Targets direct child elements of a specified parent.
Example:-
ul > li {
list-style-type: none;
}
Example: Removes bullets from direct <li> children of <ul>.
Selects an element that immediately follows another element.
Example:-
h1 + p {
font-weight: bold;
}
Example: Makes the first <p> after an <h1> bold.
Selects all sibling elements that follow a specified element.
Example:-
h2 ~ p {
color: gray;
}
Example: Styles all <p> elements after an <h2> as gray.
Pseudo-classes define a special state of an element, such as :hover, :focus, or :nth-child().
Example:-
h2 ~ p {
color: gray;
}
Example: Styles all <p> elements after an <h2> as gray.
Targets specific parts of an element, like the first line, first letter, or content before/after the element.
Example:-
p::first-line {
font-weight: bold;
}
Example: Makes the first line of all paragraphs bold.
You can group multiple selectors together by separating them with a comma.
Example:-
h1, h2, h3 {
font-family: Arial, sans-serif;
}
Example: Applies the same font family to <h1>, <h2>, and <h3> elements.
These selectors provide powerful and flexible ways to style your HTML elements efficiently.
How To Add CSS Page In Html
CSS (Cascading Style Sheets) can be added to HTML in three main ways: inline, internal, and external. Each method is suited to different needs and has its advantages. Let’s go over each method with examples.
- Inline CSS
- Inline CSS applies styles directly within an HTML element’s style attribute. This is useful for applying a unique style to a single element.
- In this example, the <h1> element is styled directly with color and font-size properties.
- Internal CSS
- Internal CSS is added within the <style> tag inside the <head> section of the HTML document. It applies styles to elements on the same page.
- Here, the styles for <h1> and <p> apply to all matching elements on the page.
- External CSS
- External CSS involves linking an external .css file to the HTML document. This is the most efficient method for larger websites as it allows you to apply the same styles to multiple pages.
- Create an external CSS file (styles.css):
- Link the CSS file to your HTML document:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inline CSS Example</title>
</head>
<body>
<h1 style="color: blue; font-size: 24px;">Hello, World!</h1>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Internal CSS Example</title>
<style>
h1 {
color: green;
font-size: 24px;
}
p {
color: gray;
font-size: 16px;
}
</style>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is an example of internal CSS.</p>
</body>
</html>
Example:-
/* styles.css */
h1 {
color: red;
font-size: 24px;
}
p {
color: black;
font-size: 18px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>External CSS Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Hello, World!</h1>
<p>This is an example of external CSS.</p>
</body>
</html>
By using <link rel="stylesheet" href="styles.css"> in the <head> section, the CSS from styles.css is applied to the HTML page.
Syntax for CSS Comments
CSS comments are notes added to stylesheets for documentation or clarification, enclosed within /* and */. They do not affect the code’s functionality and are ignored by browsers, making them useful for explaining styles, organizing sections, or temporarily disabling code during debugging.
Key Points
- CSS Comment Start: /*
- CSS Comment End: */
- Single-line and Multi-line: CSS comments can be single or multi-line, as long as they are enclosed within /* and */.
Common Uses of CSS Comments
/* This is a single-line CSS comment */
h1 {
color: blue; /* This comment is at the end of a line */
}
/*
This is a multi-line comment in CSS.
It can span multiple lines.
*/
p {
font-size: 16px;
color: gray;
}
/* Temporarily Disable Code: */
/* h2 {
color: red;
} */
CSS Colors
- Text Color
- The color property is used to set the color of the text content within an element. You can use color names, hex codes, RGB, RGBA, HSL, or HSLA values.
- Background Color
- The background-color property is used to set the background color of an element. This can be applied to most elements like divs, buttons, sections, and more.
- Border Color
- The border-color property sets the color of the border around an element. You can use color values directly with border-color or specify it as part of the shorthand border property along with width and style.
/* Sets the text color to blue */
p {
color: blue;
}
/* Sets the text color to a specific hex value */
h1 {
color: #FF5733;
}
/* Sets the text color with RGBA, allowing transparency */
span {
color: rgba(0, 128, 0, 0.8);
}
/* Sets the background color to light gray */
div {
background-color: lightgray;
}
/* Sets the background color using HSL */
section {
background-color: hsl(120, 60%, 70%);
}
/* Transparent background using RGBA */
header {
background-color: rgba(255, 0, 0, 0.3);
}
/* Sets border color only */
.box {
border-style: solid;
border-width: 2px;
border-color: #3498db;
}
/* Using shorthand to set color with width and style */
button {
border: 2px solid purple;
}
/* Different colors for each side of the border */
.container {
border-top-color: red;
border-right-color: green;
border-bottom-color: blue;
border-left-color: orange;
border-style: solid;
border-width: 2px;
}
CSS Backgrounds
In CSS, the background of an element can be customized in multiple ways using different background properties. Here’s an overview of the main types and how they work.
Types of Background Properties
- Background Color
- The background-color property sets a solid color for an element’s background. This can use color names, hex codes, RGB, RGBA, HSL, or HSLA.
- Background Image
- The background-image property allows you to set an image as the background of an element. The URL of the image is specified using url().
- Background Repeat
- The background-repeat property controls whether and how the background image is repeated (tiled). Options include repeat, no-repeat, repeat-x, and repeat-y.
- Background Position
- The background-position property specifies the starting position of the background image. Values include keywords (e.g., top, bottom, center), percentages, or pixel values.
- Background Size
- The background-size property controls the scaling of the background image. Options include cover, contain, or specific pixel/percentage values.
- cover: Scales the image to cover the entire area.
- contain: Scales the image to fit within the area.
- Background Attachment
- The background-attachment property controls whether the background image scrolls with the page or stays fixed. Options include scroll, fixed, and local.
- Background Clip
- The background-clip property determines the area within which the background is painted. Options include border-box, padding-box, and content-box.
- Background Origin
- The background-origin property specifies where the background positioning starts. It also has options of border-box, padding-box, and content-box.
- Multiple Backgrounds
- CSS allows multiple background images for a single element, separated by commas. Each background image can have its own settings for size, position, etc.
div {
background-color: lightblue;
}
body {
background-image: url('background.jpg');
}
div {
background-image: url('pattern.png');
background-repeat: repeat-x; /* Repeats horizontally only */
}
header {
background-image: url('header-bg.jpg');
background-position: center;
}
header {
background-image: url('header-bg.jpg');
background-position: center;
}
body {
background-image: url('background.jpg');
background-attachment: fixed; /* Background remains fixed */
}
div {
background-color: lightcoral;
background-clip: padding-box; /* Background only within padding area */
}
div {
background-image: url('image.jpg');
background-origin: content-box; /* Image starts at content box */
}
div {
background-image: url('image1.png'), url('image2.png');
background-position: left top, right bottom;
background-repeat: no-repeat, no-repeat;
}
CSS Borders
CSS borders are a versatile way to style the edges of HTML elements. You can control their color, width, style, and even add multiple borders. Here’s a look at the main types of CSS borders and how they work with examples.
- Border Style
- The border-style property defines the type of line used for the border. Border styles include:
- solid: A single, solid line.
- dotted: A dotted line.
- dashed: A dashed line.
- double: A double line.
- none: No border.
- groove, ridge, inset, and outset: 3D-styled borders.
- Border Width
- The border-width property sets the thickness of the border. You can use values in pixels, ems, or keywords (thin, medium, thick).
- Border Color
- The border-color property changes the color of the border. You can use named colors, hex values, RGB, or HSL.
- Border Radius
- The border-radius property rounds the corners of a border. It can be set to a percentage or pixel value, allowing for everything from slightly rounded corners to fully circular borders.
- Individual Border Sides
- CSS allows setting different border properties for each side of an element: border-top, border-right, border-bottom, and border-left.
- Shorthand Border Property
- The border shorthand property lets you define the border’s style, width, and color all at once.
- Multiple Borders (Using Outlines or Box Shadow)
- To create multiple borders, you can use a combination of outline and box-shadow along with border.
- Example of Different Borders:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Border Types</title>
<style>
.box {
width: 200px;
padding: 10px;
margin: 10px;
}
.solid { border: 3px solid black; }
.dotted { border: 3px dotted black; }
.dashed { border: 3px dashed black; }
.double { border: 3px double black; }
.groove { border: 3px groove black; }
.ridge { border: 3px ridge black; }
.inset { border: 3px inset black; }
.outset { border: 3px outset black; }
</style>
</head>
<body>
<div class="box solid">Solid Border</div>
<div class="box dotted">Dotted Border</div>
<div class="box dashed">Dashed Border</div>
<div class="box double">Double Border</div>
<div class="box groove">Groove Border</div>
<div class="box ridge">Ridge Border</div>
<div class="box inset">Inset Border</div>
<div class="box outset">Outset Border</div>
</body>
</html>
.box-thin {
border-style: solid;
border-width: thin;
}
.box-thick {
border-style: solid;
border-width: thick;
}
.box-custom {
border-style: solid;
border-width: 5px;
}
.box-red {
border-style: solid;
border-width: 2px;
border-color: red;
}
.box-gradient {
border-style: solid;
border-width: 2px;
border-color: rgba(0, 128, 0, 0.5);
}
.box-rounded {
border: 2px solid black;
border-radius: 10px;
}
.box-circle {
border: 2px solid black;
border-radius: 50%; /* Makes element circular */
}
.box-individual {
border-top: 2px solid red;
border-right: 4px dashed blue;
border-bottom: 3px dotted green;
border-left: 5px double orange;
}
.box-shorthand {
border: 3px solid purple; /* Width, style, and color in one line */
}
.box-multiple-borders {
border: 3px solid black;
outline: 3px dashed red;
box-shadow: 0 0 0 6px yellow; /* Additional outer border */
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Borders Example</title>
<style>
.box-rounded { border: 2px solid blue; border-radius: 10px; }
.box-individual { border-top: 2px solid red; border-right: 4px dashed green; border-bottom: 2px dotted blue; border-left: 3px solid orange; }
.box-shorthand { border: 3px solid purple; }
.box-multiple-borders { border: 3px solid black; outline: 2px dashed red; box-shadow: 0 0 0 5px yellow; }
</style>
</head>
<body>
<div class="box-rounded">Rounded Border</div>
<div class="box-individual">Individual Border Sides</div>
<div class="box-shorthand">Shorthand Border</div>
<div class="box-multiple-borders">Multiple Borders</div>
</body>
</html>
CSS Margins
CSS margins create space outside of an HTML element’s border, allowing you to control the distance between elements. Margins can be set individually for each side (top, right, bottom, left) or all sides at once
- The margin Shorthand Property
- The margin property sets the margin for all four sides in one line:
- margin: 10px; — all sides 10px.
- margin: 10px 20px; — vertical (top & bottom) 10px, horizontal (left & right) 20px.
- margin: 10px 20px 30px; — Top margin 10px,right and left (horizontal) margins 20px and bottom margin 30px.
- margin: 10px 20px 30px 40px; — all sides (top, right, bottom, left).
- Individual Margins
- You can also set margins for each side individually:
- margin-top: Space above the element.
- margin-right: Space to the right of the element.
- margin-bottom: Space below the element.
- margin-left: Space to the left of the element.
- Auto Margin for Centering
- Setting horizontal margins (margin-left and margin-right) to auto will center an element within its container, as long as the element has a defined width.
- Negative Margins
- Negative values for margins are allowed and pull elements closer to their neighboring elements, or even overlapping them.
- Margin Collapse
- CSS Margin Collapse is a behavior where the vertical margins of adjacent block-level elements (top and bottom margins) combine into a single margin instead of adding up. This results in only the larger of the two margins being applied. Margin collapse helps simplify layouts by preventing unnecessary spacing between elements.
.container1 {
margin: 10px;
}
.container2 {
margin: 10px 20px;
}
.container3 {
margin: 10px 20px 30px;
}
.container4 {
margin: 10px 20px 30px 40px;
}
.box {
margin-top: 20px;
margin-right: 15px;
margin-bottom: 20px;
margin-left: 15px;
}
.centered-box {
width: 50%;
margin-left: auto;
margin-right: auto;
}
.overlapping-box {
margin-top: -10px;
margin-left: -5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Margin Collapse Example</title>
<style>
.box1 {
background-color: lightblue;
height: 100px;
margin-bottom: 30px; /* Margin below the first box */
}
.box2 {
background-color: lightcoral;
height: 100px;
margin-top: 20px; /* Margin above the second box */
}
</style>
</head>
<body>
<div class="box1">Box 1</div>
<div class="box2">Box 2</div>
</body>
</html>
CSS Padding
CSS Padding is the space between an element’s content and its border. It creates inner space within the element, pushing content away from the edges. Padding can be set on all sides at once or individually for each side (top, right, bottom, left).
- Shorthand Padding Property
- Using the padding shorthand, you can define padding for all sides in one line:
- padding: 10px; — all sides 10px padding.
- padding: 10px 20px; — vertical (top & bottom) 10px, horizontal (left & right) 20px.
- padding: 10px 20px 30px; — Top padding 10px,right and left (horizontal) padding 20px and bottom padding 30px.
- padding: 10px 20px 30px 40px; — all sides (top, right, bottom, left).
- Individual Padding Properties
- You can set padding for each side individually:
- Example of CSS Padding in HTML:-
.container {
padding: 10px 20px 30px 40px;
}
.box {
padding-top: 10px;
padding-right: 20px;
padding-bottom: 10px;
padding-left: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Padding Example</title>
<style>
.box {
background-color: lightblue;
padding: 20px; /* Adds 20px padding on all sides */
border: 2px solid blue;
}
</style>
</head>
<body>
<div class="box">This box has padding inside, creating space between the content and border.</div>
</body>
</html>
CSS Height, Width and Max-width
In CSS, height, width, and max-width properties control the size of elements, helping to create flexible layouts that respond well to different screen sizes and resolutions.
- width and height
- The width and height properties set the width and height of an element. These properties can use values in units like pixels (px), percentages (%), or view units (vw and vh for viewport width and height).
- width: Sets the horizontal size of an element.
- height: Sets the vertical size of an element.
- max-width
- The max-width property defines the maximum allowable width for an element, helping create responsive layouts. If the content is smaller than max-width, the element shrinks to fit the content. If it grows beyond max-width, the element’s width is restricted to the defined value.
- max-width: Useful for responsive layouts to prevent elements from growing too large on larger screens.
- Example Using Width, Height, and Max-width:-
- Note:
max-width Limits an element’s width, preventing it from expanding beyond a certain point, ideal for responsive designs.
.box {
width: 300px; /* Fixed width */
height: 200px; /* Fixed height */
}
.responsive-box {
width: 50%; /* Width is 50% of the parent container */
height: 100vh; /* Height is full viewport height */
}
.container {
max-width: 100%; /* Ensures the element never exceeds its container's width */
}
.image {
width: 100%;
max-width: 600px; /* Restricts image width to 600px on larger screens */
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Width, Height, and Max-width</title>
<style>
.fixed-box {
width: 300px;
height: 150px;
background-color: lightblue;
}
.responsive-box {
width: 80%;
max-width: 500px; /* Restricts max width to 500px */
background-color: lightcoral;
padding: 20px;
}
</style>
</head>
<body>
<div class="fixed-box">This box has a fixed width and height.</div>
<div class="responsive-box">This box adjusts to 80% of the container but maxes out at 500px width.</div>
</body>
</html>
CSS Box Model
The CSS Box Model defines how an element’s content, padding, border, and margin combine to determine its total size and spacing on a webpage.
Layers of the CSS Box Model
- Content: The area where text, images, or other content is displayed; controlled by width and height.
- Padding: Space between the content and border, creating inner space within the element. Padding can be customized for each side.
- Border: Surrounds padding and content, creating an outline around the element. Border width, style, and color are customizable.
- Margin: The outermost layer, creating space between the element and neighboring elements. Margins can collapse when adjacent elements meet.
- Content width: 300px.
- Total width including padding and border: 300px + (20px * 2 padding) + (2px * 2 border) = 344px.
- Total space taken by the element (including margin): 344px + (15px * 2 margin) = 374px.
Visualization of the CSS Box Model
Example:-
.box {
width: 300px; /* Width of the content area */
padding: 20px; /* Padding around content */
border: 2px solid black; /* Border width and style */
margin: 15px; /* Margin around the box */
}
Box-Sizing Property
The box-sizing property can change how the box model is calculated:
- content-box (default): Only the content width/height is defined by width and height properties. Padding and border add extra space to the element.
- border-box: Width and height include content, padding, and border, making the element’s total width and height stay as defined.
Example of box-sizing: border-box:
.box {
width: 300px;
padding: 20px;
border: 2px solid black;
box-sizing: border-box; /* Total width stays at 300px */
}
CSS Outline
The CSS Outline properties allow you to create a line around elements, which is particularly useful for highlighting elements when they are focused or interacted with. Unlike borders, outlines do not occupy space in the document flow, making them a flexible option for styling. Below are the main outline properties explained with examples.
- outline
- The outline property is a shorthand property for setting all the individual outline properties in one declaration. It can include the width, style, and color of the outline.
- outline-color
- The outline-color property sets the color of the outline. If no color is specified, it defaults to the color of the element's text.
- outline-style
- The outline-style property specifies the style of the outline. Common styles include solid, dashed, dotted, double, and none.
- outline-width
- The outline-width property defines the width of the outline. You can use specific values like thin, medium, and thick, or you can specify a length (e.g., 2px).
- outline-offset
- The outline-offset property sets the space between the outline and the border edge of the element. This property can create a visual separation between the outline and the element itself.
Syntax:-
outline: [outline-width] [outline-style] [outline-color];
Example:-
.button {
outline: 2px solid blue; /* 2 pixels wide, solid line, blue color */
}
.input-field {
outline: 2px solid; /* Default color (usually black) */
outline-color: red; /* Setting the outline color to red */
}
.alert {
outline: 3px dashed orange; /* 3 pixels wide, dashed line, orange color */
}
.box {
outline-width: thick; /* Setting the outline to a thick width */
outline-style: solid;
outline-color: green;
}
.card {
outline: 2px solid black;
outline-offset: 10px; /* Creates a 10px space between outline and element */
}
Complete Example:-
Here’s a complete HTML and CSS example demonstrating all the outline properties:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Outline Properties</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.button {
padding: 10px 20px;
background-color: #4CAF50; /* Green */
color: white;
border: none;
outline: 2px solid blue; /* Outline with width, style, color */
cursor: pointer;
}
.input-field {
padding: 10px;
margin-top: 20px;
outline: 2px solid;
outline-color: red; /* Red outline color */
}
.alert {
padding: 15px;
background-color: #ffeb3b; /* Yellow background */
outline: 3px dashed orange; /* Dashed outline */
}
.box {
padding: 20px;
margin-top: 20px;
outline-width: thick; /* Thick outline */
outline-style: solid;
outline-color: green; /* Green outline */
}
.card {
padding: 30px;
margin-top: 20px;
outline: 2px solid black; /* Black outline */
outline-offset: 10px; /* Space between outline and box */
}
</style>
</head>
<body>
<button class="button">Click Me!</button>
<input type="text" class="input-field" placeholder="Type here...">
<div class="alert">This is an alert box!</div>
<div class="box">This is a box with a thick outline.</div>
<div class="card">This is a card with an outline offset.</div>
</body>
</html>
CSS Text
In CSS, text properties allow you to style and control the appearance of text on your webpage. With these properties, you can adjust the font, size, alignment, color, spacing, and decoration of text elements. Here’s a breakdown of some essential CSS text properties:
- Text Color
- color: Sets the color of the text.
- Text Alignment
- text-align: Controls the alignment of text within its container. Options include left, right, center, and justify.
- Text Decoration
- Underline (text-decoration: underline;)
- Overline (text-decoration: overline;)
- Line-Through (text-decoration: line-through;)
- None (text-decoration: none;)
- Multiple Decorations (text-decoration: underline overline;)
- text-decoration-color: Specifies the color of the text decoration.
- text-decoration-style: Sets the style of the decoration, such as solid, double, dotted, dashed, or wavy.
- text-decoration-thickness: Adjusts the thickness of the text decoration (available in some browsers).
- Text Transformation
- none
- capitalize
- uppercase
- lowercase
- Letter and Word Spacing
- Letter Spacing
- Word Spacing
- Line Height
- Text Indentation
- White Space
- Font Style and Weight
- Text Shadow
.named-color {
color: red; /* Named color */
}
.hex-color {
color: #FF5733; /* Hexadecimal color */
}
.rgb-color {
color: rgb(60, 179, 113); /* RGB color */
}
.rgba-color {
color: rgba(60, 179, 113, 0.7); /* RGB color with opacity */
}
.hsl-color {
color: hsl(240, 100%, 50%); /* HSL color */
}
.hsla-color {
color: hsla(240, 100%, 50%, 0.5); /* HSL color with opacity */
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text Alignment Types</title>
<style>
.left-align { text-align: left; }
.right-align { text-align: right; }
.center-align { text-align: center; }
.justify-align { text-align: justify; }
.start-align { text-align: start; }
.end-align { text-align: end; }
</style>
</head>
<body>
<h2>Examples of Text Alignment</h2>
<p class="left-align">Left-aligned text: This text is aligned to the left side of the container.</p>
<p class="right-align">Right-aligned text: This text is aligned to the right side of the container.</p>
<p class="center-align">Center-aligned text: This text is centered within the container.</p>
<p class="justify-align">Justified text: This text is justified to cover the full width of the container, creating evenly spaced words for a clean look in paragraphs.</p>
<p class="start-align">Start-aligned text: This text aligns to the start of the document direction.</p>
<p class="end-align">End-aligned text: This text aligns to the end of the document direction.</p>
</body>
</html>
The text-decoration property in CSS is used to add various decorative effects to text, such as underlines, overlines, line-throughs, and more. It allows you to control whether text decorations are applied and customize their style, color, and thickness.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Types of CSS Text Decoration</title>
<style>
.underline {
text-decoration: underline;
}
.overline {
text-decoration: overline;
}
.line-through {
text-decoration: line-through;
}
.no-decoration {
text-decoration: none;
}
.underline-overline {
text-decoration: underline overline;
}
</style>
</head>
<body>
<h2>Examples of Text Decoration</h2>
<p class="underline">This text has an underline.</p>
<p class="overline">This text has an overline.</p>
<p class="line-through">This text has a line-through.</p>
<a href="#" class="no-decoration">This link has no underline.</a>
<p class="underline-overline">This text has both underline and overline.</p>
</body>
</html>
Additional Properties with text-decoration
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Additional Properties with text-decoration</title>
<style>
.colored-underline {
text-decoration: underline;
text-decoration-color: red;
}
.dashed-underline {
text-decoration: underline;
text-decoration-style: dashed;
}
.thick-underline {
text-decoration: underline;
text-decoration-thickness: 3px;
}
</style>
</head>
<body>
<h2>Examples of Additional Properties with text-decoration</h2>
<p class="colored-underline">This text has a red underline.</p>
<p class="dashed-underline">This text has a dashed underline.</p>
<p class="thick-underline">This text has a thick underline.</p>
</body>
</html>
The text-transform property in CSS controls the capitalization of text within an element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Text Transformation Example</title>
<style>
.no-transform { text-transform: none; }
.capitalize { text-transform: capitalize; }
.uppercase { text-transform: uppercase; }
.lowercase { text-transform: lowercase; }
</style>
</head>
<body>
<h2>Examples of Text Transformation</h2>
<p class="no-transform">This text has no transformation.</p>
<p class="capitalize">this text will be capitalized.</p>
<p class="uppercase">this text will be in uppercase.</p>
<p class="lowercase">THIS TEXT WILL BE IN LOWERCASE.</p>
</body>
</html>
CSS provides several properties for controlling text spacing, which help with readability and visual presentation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Text Spacing Example</title>
<style>
.letter-spacing { letter-spacing: 2px; }
.word-spacing { word-spacing: 5px; }
.line-height { line-height: 1.8; }
.text-indent { text-indent: 30px; }
.nowrap { white-space: nowrap; }
</style>
</head>
<body>
<h2>Examples of Text Spacing Properties</h2>
<p class="letter-spacing">This text has increased letter spacing.</p>
<p class="word-spacing">This text has increased word spacing.</p>
<p class="line-height">This paragraph has a taller line height, giving more vertical space between lines of text.</p>
<p class="text-indent">This paragraph has an indentation at the start of the first line.</p>
<p class="nowrap">This text has no wrapping, so it stays on one line.</p>
</body>
</html>
The font-style property in CSS specifies the style of the text (normal, italic, oblique), while the font-weight property determines the thickness of the text (normal, bold, or numeric values). These properties are used to enhance text appearance.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Font Style and Weight Example</title>
<style>
.styled-text {
font-style: italic; /* Italic style */
font-weight: bold; /* Bold weight */
}
</style>
</head>
<body>
<p class="styled-text">This text is italic and bold.</p>
</body>
</html>
The text-shadow property in CSS allows you to add shadows to text, giving it a three-dimensional or stylistic appearance. This property supports multiple shadows, each with adjustable position, blur radius, and color.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Text Shadow Examples</title>
<style>
<!-- Format: text-shadow: offsetX offsetY color; -->
.basic-shadow { text-shadow: 2px 2px gray; }
<!-- Format: text-shadow: offsetX offsetY blurRadius color; -->
.blurred-shadow { text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.5); }
<!-- Format: text-shadow: offsetX1 offsetY1 blurRadius1 color1, offsetX2 offsetY2 blurRadius2 color2, ...; -->
.multiple-shadows { text-shadow: 1px 1px 2px black, -1px -1px 2px red; }
.inset-shadow { text-shadow: 0px 1px 2px black; }
.glow { color: #fff; text-shadow: 0px 0px 8px #ff00ff; }
.three-d { text-shadow: 1px 1px #555, 2px 2px #333, 3px 3px #111; }
</style>
</head>
<body>
<h2>CSS Text Shadow Examples</h2>
<p class="basic-shadow">Basic shadow effect.</p>
<p class="blurred-shadow">Blurred shadow effect.</p>
<p class="multiple-shadows">Multiple shadows effect.</p>
<p class="inset-shadow">Faux inset shadow effect.</p>
<p class="glow">Glowing text effect.</p>
<p class="three-d">3D text shadow effect.</p>
</body>
</html>
CSS Fonts
CSS fonts are essential for controlling the typography of web pages, enabling designers to specify the font families, sizes, weights, and styles for text elements. Here’s a breakdown of how to use CSS to manage fonts effectively:
- Font Families
- You can specify a font family using the font-family property. It's best practice to include a fallback list of font families.
- Font Size
- The font-size property sets the size of the font. You can use various units like px, em, rem, %, etc.
- Web Fonts
- To use custom fonts, you can import them via @font-face or use services like Google Fonts.
- Responsive Typography
- Using viewport units (vw, vh) or CSS clamp() allows for more responsive typography.
body {
font-family: 'Arial', 'Helvetica', sans-serif; /* Fallbacks */
}
h1 {
font-size: 2em; /* Relative to the parent element */
}
p {
font-size: 16px; /* Absolute size */
}
Using @font-face:
@font-face {
font-family: 'MyCustomFont';
src: url('MyCustomFont.woff2') format('woff2'),
url('MyCustomFont.woff') format('woff');
font-weight: normal;
font-style: normal;
}
body {
font-family: 'MyCustomFont', sans-serif;
}
CSS Icons
- Font Icons
- Step 1: Include Font Awesome
(Add the following line to the <head> section of your HTML document to link to Font Awesome): - Step 2: Use Icons in Your HTML
(You can now use Font Awesome icons by including the appropriate class names in <i> or <span> elements. Here’s a simple example where we create a navigation menu with icons): - SVG Icons
- Certainly! Here’s an example of using SVG icons directly within HTML. SVGs are great because they’re scalable, lightweight, and can be styled with CSS.
- Using SVG Icons Inline
(In this example, we’ll use a simple SVG icon (a star) as part of a rating system.): - CSS Pseudo-Elements for Icons
- Certainly! Here’s an example of using CSS pseudo-elements (::before or ::after) to create an icon for a button. This technique is lightweight and perfect for adding small, decorative icons without adding extra HTML elements.
- Adding a Simple Home Icon with CSS Pseudo-Elements
In this example, we’ll use a Unicode character for a "home" icon to style a navigation button. - Image Icons (PNG, JPEG, GIF)
- In this example, we’ll display a small "search" icon (as a PNG file) next to a search input field.
- CSS Background Image Icons
- Certainly! Here’s an example of using a CSS background image icon. This method is useful for adding decorative icons without extra HTML elements and can be handy for buttons, links, or list items.
- In this example, we’ll create a "download" button with a PNG icon as the background image.
- Favicons (HTML Head Icons)
- Certainly! Here’s an example of adding a favicon to your website. Favicons are small icons displayed in the browser tab, bookmarks, or other browser areas, helping with brand recognition and easy navigation.
- Create or download an icon image. It’s common to use a 16x16 or 32x32 pixel image saved as .ico, .png, or .svg.
- Name it favicon.ico (the standard name for favicon files) and place it in your website’s root directory.
- Add the following code in the <head> section of your HTML document:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<title>Font Awesome Icons Example</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
padding: 20px;
}
.nav {
list-style-type: none;
padding: 0;
}
.nav li {
margin: 10px 0;
}
.nav a {
text-decoration: none;
color: #333;
display: flex;
align-items: center;
}
.nav a i {
margin-right: 8px; /* Space between icon and text */
color: #007bff; /* Icon color */
}
</style>
</head>
<body>
<h2>Navigation Menu</h2>
<ul class="nav">
<li><a href="#"><i class="fas fa-home"></i> Home</a></li>
<li><a href="#"><i class="fas fa-user"></i> Profile</a></li>
<li><a href="#"><i class="fas fa-cog"></i> Settings</a></li>
<li><a href="#"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
</ul>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SVG Icon Example</title>
<style>
.rating {
display: flex;
align-items: center;
}
.star {
width: 24px; /* Icon width */
height: 24px; /* Icon height */
fill: #ffcc00; /* Star color */
margin-right: 4px;
cursor: pointer;
transition: fill 0.3s ease;
}
.star:hover {
fill: #ff9900; /* Hover color */
}
</style>
</head>
<body>
<h2>Rating:<h2>
<div class="rating">
<svg class="star" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M12 2L14.9 8.7L22 9.3L16.6 14L18.4 21L12 17.3L5.6 21L7.4 14L2 9.3L9.1 8.7L12 2z"/>
</svg>
<svg class="star" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M12 2L14.9 8.7L22 9.3L16.6 14L18.4 21L12 17.3L5.6 21L7.4 14L2 9.3L9.1 8.7L12 2z"/>
</svg>
<svg class="star" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M12 2L14.9 8.7L22 9.3L16.6 14L18.4 21L12 17.3L5.6 21L7.4 14L2 9.3L9.1 8.7L12 2z"/>
</svg>
<svg class="star" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M12 2L14.9 8.7L22 9.3L16.6 14L18.4 21L12 17.3L5.6 21L7.4 14L2 9.3L9.1 8.7L12 2z"/>
</svg>
<svg class="star" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M12 2L14.9 8.7L22 9.3L16.6 14L18.4 21L12 17.3L5.6 21L7.4 14L2 9.3L9.1 8.7L12 2z"/>
</svg>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Pseudo-Elements Icon Example</title>
<style>
/* Styling the button */
.icon-button {
display: inline-flex;
align-items: center;
font-size: 16px;
padding: 10px 15px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-family: Arial, sans-serif;
}
/* Adding an icon with ::before pseudo-element */
.icon-button::before {
content: "🏠"; /* Unicode for house icon */
font-size: 18px;
margin-right: 8px; /* Space between icon and text */
}
</style>
</head>
<body>
<button class="icon-button">Home</button>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Icon Example</title>
<style>
/* Styling for the search container */
.search-container {
display: flex;
align-items: center;
border: 1px solid #ddd;
padding: 5px;
border-radius: 5px;
max-width: 300px;
}
/* Styling for the search icon */
.search-icon {
width: 20px; /* Width of the icon */
height: 20px; /* Height of the icon */
margin-right: 8px; /* Space between icon and input */
}
/* Styling for the input field */
.search-input {
border: none;
outline: none;
font-size: 16px;
width: 100%;
}
</style>
</head>
<body>
<div class="search-container">
<!-- Image icon as PNG -->
<img src="search-icon.png" alt="Search" class="search-icon">
<input type="text" placeholder="Search..." class="search-input">
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Background Image Icon Example</title>
<style>
/* Styling for the download button */
.download-button {
display: inline-flex;
align-items: center;
padding: 10px 15px;
font-size: 16px;
color: white;
background-color: #28a745;
border: none;
border-radius: 5px;
cursor: pointer;
font-family: Arial, sans-serif;
background-image: url('download-icon.png'); /* Path to the image */
background-repeat: no-repeat; /* Prevents the icon from repeating */
background-position: left center; /* Positions the icon on the left */
background-size: 20px 20px; /* Sets the icon size */
padding-left: 40px; /* Space for the icon */
}
</style>
</head>
<body>
<button class="download-button">Download</button>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Favicon Example</title>
<!-- Favicon Link -->
<link rel="icon" href="favicon.ico" type="image/x-icon">
<!-- Alternative formats for favicon -->
<!-- For PNG -->
<link rel="icon" href="favicon.png" type="image/png" sizes="32x32">
<!-- For SVG -->
<link rel="icon" href="favicon.svg" type="image/svg+xml">
</head>
<body>
<h1>Hello, World!</h1>
<p>Check the browser tab for the favicon.</p>
</body>
</html>
CSS Links
- In CSS, links can be styled using pseudo-classes to control their appearance based on their state (e.g., normal, hover, active, visited). Here’s an overview of styling links in CSS:
- CSS provides several pseudo-classes for styling links in different states
- :link: Styles unvisited links.
- :visited: Styles links that have already been visited by the user.
- :hover: Styles links when the mouse pointer hovers over them.
- :active: Styles links at the moment they are clicked or activated.
Syntax for Styling Text Links
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Link Styles</title>
<style>
/* Basic link styles */
a:link {
color: #007bff; /* Blue for unvisited links */
text-decoration: none;
}
a:visited {
color: #6c757d; /* Gray for visited links */
}
a:hover {
color: #0056b3; /* Darker blue on hover */
text-decoration: underline; /* Underline on hover */
}
a:active {
color: #dc3545; /* Red when active (clicked) */
}
</style>
</head>
<body>
<p>
<a href="https://www.example.com" target="_blank">Visit Example Site</a>
</p>
</body>
</html>
Syntax for Styling Link Button
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Link Button</title>
<style>
/* Basic styling for link buttons */
.btn {
display: inline-block; /* Makes the link behave like a button */
padding: 10px 20px; /* Space inside the button */
font-size: 16px;
color: white; /* Text color */
background-color: #007bff; /* Button color */
text-decoration: none; /* Removes underline from the link */
border-radius: 5px; /* Rounded corners */
transition: background-color 0.3s; /* Smooth hover effect */
}
/* Hover effect */
.btn:hover {
background-color: #0056b3; /* Darker color on hover */
}
</style>
</head>
<body>
<a href="#" class="btn">Click Me</a>
</body>
</html>
CSS Lists
In CSS, lists are customized using properties that modify the appearance of both ordered (<ol>) and unordered (<ul>) lists. Common list properties include list-style-type, list-style-image, and list-style-position.
- Unordered Lists (<ul>)
- Description: An unordered list displays items without any particular order, commonly styled with bullets (such as circles, squares, or custom images).
- CSS Properties:
- list-style-type: Sets the bullet style (e.g., disc, circle, quare).
- list-style-image: Allows replacing bullets with an image.
- list-style-position: Places bullets inside or outside the text.
- Ordered Lists (<ol>)
- Description: An ordered list displays items in a specific sequence, typically numbered or lettered (such as 1, 2, 3 or A, B, C).
- CSS Properties:
- list-style-type: Sets the numbering style (e.g., decimal, upper-alpha, lower-roman).
- list-style-image: Adds a custom image marker (not commonly used in ordered lists).
- list-style-position: Positions the numbering inside or outside the text area.
- Shorthand Property
- list-style (Shorthand): Combines the three properties (list-style-type, list-style-image, and list-style-position) in a single line.
ul {
list-style-image: url('marker.png');
}
ul {
list-style-position: inside;
}
<ul style="list-style-type: square;">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
ol {
list-style-image: url('marker.png');
}
ol {
list-style-position: inside;
}
<ol style="list-style-type: upper-alpha;">
<li>Step A</li>
<li>Step B</li>
<li>Step C</li>
</ol>
ul {
list-style: square inside;
}
Example:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Lists Example</title>
<style>
/* Unordered list with square bullets inside */
ul.custom-ul {
list-style-type: square;
list-style-position: inside;
}
/* Ordered list with Roman numerals and image markers */
ol.custom-ol {
list-style-type: upper-roman;
list-style-image: url('marker.png');
}
</style>
</head>
<body>
<h2>Unordered List with Custom Style</h2>
<ul class="custom-ul">
<li>List item one</li>
<li>List item two</li>
<li>List item three</li>
</ul>
<h2>Ordered List with Custom Style</h2>
<ol class="custom-ol">
<li>List item one</li>
<li>List item two</li>
<li>List item three</li>
</ol>
</body>
</html>
CSS Tables
CSS tables are used to style HTML tables, enhancing their readability and visual structure. With CSS, you can customize aspects like borders, padding, layout, and alignment, making tables easier to interpret.
Example of basic table
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple HTML Table</title>
</head>
<body>
<h2>Student Grades</h2>
<table border="1">
<tr>
Name
<th>Subject</th>
<th>Grade</th>
</tr>
<tr>
<td>Alice</td>
<td>Math</td>
<td>A</td>
</tr>
<tr>
<td>Bob</td>
<td>Science</td>
<td>B</td>
</tr>
<tr>
<td>Charlie</td>
<td>History</td>
<td>C</td>
</tr>
</table>
</body>
</html>
- Basic Table Styling
- Description: Basic styling properties control borders, padding, and alignment within table cells.
- Common Properties:
- border: Sets the table border style (e.g., solid, dashed).
- padding: Adds space inside each cell.
- text-align: Aligns the text in each cell (left, center, right).
- Border Collapsed vs. Separated Tables
- Description: Controls whether table borders are collapsed into a single border or separated.
- Property:
- border-collapse: Defines how cell borders are displayed. Options:
- collapse: Merges adjacent cell borders into a single border.
- separate: Keeps borders separate for each cell.
- Table Width and Height
- Description: Sets the overall size of the table and adjusts column width or row height.
- Property:
- width: Sets the width of the entire table or specific columns.
- height: Sets the table or row height.
- Table Layout
- Description: Controls how table cells are sized, especially when dealing with dynamic content.
- Property:
- table-layout: Specifies the algorithm used to determine the layout of a table.
- auto: The table is automatically sized based on content.
- fixed: The width of columns is fixed, allowing faster layout rendering.
- Styling Alternating Rows (Zebra Stripes)
- Description: Adds alternating row colors for better readability.
- Method:Use nth-child selector to apply styles to odd/even rows.
- Caption Styling
- Description: Styles the table caption, which is the title or heading of the table.
- Properties:
- caption-side: Sets the caption above or below the table (top or bottom).
- text-align: Aligns the caption text.
- Column and Row Grouping
- Description: Styles specific columns or groups of rows with <colgroup> and <thead>, <tbody>, <tfoot>.
- Method:Use
for column styling and <thead>, <tbody>, <tfoot> for row grouping. - Table of CSS Table Properties:
table, th, td {
border: 1px solid black;
padding: 8px;
}
table {
border-collapse: collapse; /* Or 'separate' */
}
table {
width: 100%; /* Full width of the container */
}
table {
table-layout: fixed;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
caption {
caption-side: top;
font-weight: bold;
}
<table>
<colgroup>
<col style="background-color: #f2f2f2;">
</colgroup>
<thead>
<tr><td>Header</td></tr>
</thead>
<tbody>
<tr><td>Data</td></tr>
</tbody>
</table>
Example:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Styled Table Example</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #333;
padding: 10px;
text-align: left;
}
th {
background-color: #4CAF50;
color: white;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<table>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
<tr>
<td>Apple</td>
<td>$1.00</td>
</tr>
<tr>
<td>Banana</td>
<td>$0.50</td>
</tr>
<tr>
<td>Orange</td>
<td>$0.80</td>
</tr>
</table>
</body>
</html>
CSS Display Properties
The display property in CSS is used to control how an element is displayed or structured in the document layout. It defines the layout behavior of an element, impacting how it interacts with other elements in the DOM. Here’s a brief overview of common types of display values:
- display: block
- Behavior: Elements take up the full width available, start on a new line, and push other elements to the next line.
- Examples: <div>, <p>, <h1>
- display: inline
- Behavior: Elements only take up as much width as their content requires. They do not start on a new line.
- Examples: <span>, <a>
- display: inline-block
- Behavior: Elements are inline but allow width and height settings, and margins and padding affect surrounding elements.
- Use Case: Useful for creating button-like elements or images with text alignment.
- display: none
- Behavior: The element is completely removed from the layout, occupying no space at all.
- Use Case: Hide elements without deleting them from the document structure.
- display: flex
- Behavior: Creates a flex container, allowing for flexible item alignment and spacing within the container.
- Use Case: Responsive layouts where items need to adjust positions and sizes.
- display: hidden
- Behavior: Hides the element visually but leaves the space it occupies intact.
- Use Case: Temporarily hiding elements while keeping layout intact.
Examples:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Display Property Examples</title>
<style>
/* Display block */
.block-element {
display: block;
background-color: lightblue;
padding: 10px;
margin-bottom: 10px;
}
/* Display inline */
.inline-element {
display: inline;
background-color: lightcoral;
padding: 5px;
margin: 5px;
}
/* Display inline-block */
.inline-block-element {
display: inline-block;
background-color: lightgreen;
padding: 10px;
width: 100px;
margin: 5px;
}
/* Display none */
.none-element {
display: none;
background-color: yellow;
padding: 10px;
margin: 5px;
}
/* Display flex */
.flex-container {
display: flex;
justify-content: space-around;
background-color: lavender;
padding: 10px;
}
.flex-item {
background-color: lightpink;
padding: 10px;
margin: 5px;
width: 100px;
text-align: center;
}
/* Visibility hidden */
.visibility-hidden-element {
visibility: hidden;
background-color: lightgray;
padding: 10px;
margin-top: 10px;
}
</style>
</head>
<body>
<h2>CSS Display Property Examples</h2>
<!-- display: block -->
<div class="block-element">Block Element (takes full width)</div>
<!-- display: inline -->
<span class="inline-element">Inline Element 1</span>
<span class="inline-element">Inline Element 2</span>
<!-- display: inline-block -->
<div class="inline-block-element">Inline-block 1</div>
<div class="inline-block-element">Inline-block 2</div>
<!-- display: none (does not appear) -->
<div class="none-element">This is hidden with display: none.</div>
<!-- display: flex -->
<div class="flex-container">
<div class="flex-item">Flex Item 1</div>
<div class="flex-item">Flex Item 2</div>
<div class="flex-item">Flex Item 3</div>
</div>
<!-- visibility: hidden -->
<div class="visibility-hidden-element">This element is hidden with visibility: hidden but takes up space.</div>
</body>
</html>
CSS width and max-width
In CSS, both width and max-width are used to define the size of an element, but they serve different purposes, especially when working with responsive web design.
- width:
- The width property specifies the width of an element.
- It can be set in units like px, %, em, rem, etc.
- When used in responsive design, you can set the width to a percentage to make the element resize based on the viewport.
- max-width:
- The max-width property specifies the maximum width an element can take.
- This is useful when you want an element to be responsive but not exceed a certain width, even on large screens.
- It's commonly used to prevent elements from becoming too large on wide screens.
- Base Styles (.responsive-box):
- The .responsive-box element has a width: 100%, meaning it takes up the full width of its parent container.
- The max-width: 800px ensures that the box will not grow beyond 800px in width, even on larger screens.
- The margin: 0 auto centers the box horizontally.
- Responsive Media Queries:
- For small screens (max-width: 600px), the box will take up 90% of the screen width.
- For medium screens (max-width: 1024px), the box will take up 80% of the screen width.
.element {
width: 50%; /* 50% of the container's width */
}
.element {
width: 100%; /* Takes full width of the container */
max-width: 1200px; /* But never exceeds 1200px */
}
Example:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Box</title>
<style>
/* Base styles for the box */
.responsive-box {
width: 100%; /* Take up 100% of the parent container */
max-width: 800px; /* But never exceed 800px */
background-color: #4CAF50;
padding: 20px;
margin: 0 auto; /* Center the box horizontally */
color: white;
text-align: center;
}
/* Adjust the box size for smaller screens */
@media (max-width: 600px) {
.responsive-box {
width: 90%; /* Take up 90% of the screen width on small screens */
}
}
/* Adjust the box size for medium screens */
@media (max-width: 1024px) {
.responsive-box {
width: 80%; /* Take up 80% of the screen width on medium screens */
}
}
</style>
</head>
<body>
<div class="responsive-box">
<h1>Responsive Box</h1>
<p>This box adjusts its width based on the screen size!</p>
</div>
</body>
</html>
Explanation:
CSS Position
In CSS, the position property is essential for controlling the placement of elements on a web page.
- Static
- Syntax:- position: static;
- Description: This is the default value for HTML elements. The element follows the normal document flow and is not affected by top, right, bottom, or left properties.
- Use Case: Most commonly used when you want the element to flow naturally with other elements.
- Relative
- Syntax:- position: relative;
- Description: The element is positioned relative to its original position in the document flow. You can use top, right, bottom, and left to offset it from this initial position.
- Use Case: Useful when you want to shift an element slightly from its default location without removing it from the document flow.
- Absolute
- Syntax:- position: absolute;
- Description: The element is positioned relative to its closest positioned ancestor (an ancestor with a position other than static). If no such ancestor is found, it will be positioned relative to the <html> element. top, right, bottom, and left properties can move it from this reference point.
- Use Case: Ideal for elements that need to be placed independently of the regular flow of content, such as overlays or pop-up boxes.
- Fixed
- Syntax:- position: fixed;
- Description: The element is positioned relative to the viewport, meaning it will stay in place even when the page is scrolled. top, right, bottom, and left properties control its exact position on the viewport.
- Use Case: Commonly used for sticky navigation bars or back-to-top buttons that need to remain visible regardless of scroll position.
- Sticky
- Syntax:- position: sticky;
- Description: The element behaves like a relative element until it reaches a specified scroll position, at which point it becomes fixed within its containing block. top, right, bottom, and left are used to define when the "stickiness" should start.
- Use Case: Useful for elements like headers that stay visible while scrolling down until a certain point.
- Inherit
- Syntax:- position: inherit;
- Description: The element inherits the position property of its parent element.
- Use Case: Helpful when you want an element to follow the positioning rules of its container without setting it explicitly.
- Table of CSS position Properties:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Inherit Example</title>
<style>
/* Parent with a specific position */
.parent {
position: relative; /* This sets the position context */
width: 200px;
height: 200px;
background-color: lightblue;
margin: 20px;
}
/* Child inherits position from parent */
.child {
position: inherit; /* Inherits 'relative' from the parent */
top: 20px;
left: 20px;
width: 100px;
height: 100px;
background-color: coral;
}
/* Another example with absolute positioning */
.absolute-parent {
position: absolute; /* Absolute positioning */
top: 50px;
left: 50px;
width: 200px;
height: 200px;
background-color: lightgreen;
}
.absolute-child {
position: inherit; /* Inherits 'absolute' from the parent */
top: 10px;
left: 10px;
width: 100px;
height: 100px;
background-color: darkorange;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">Inherits Relative</div>
</div>
<div class="absolute-parent">
<div class="absolute-child">Inherits Absolute</div>
</div>
</body>
</html>
Examples:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Position Examples</title>
<style>
.box {
width: 100px;
height: 100px;
margin: 10px;
color: white;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
}
/* Static */
.static-box {
position: static;
background-color: gray;
}
/* Relative */
.relative-box {
position: relative;
top: 20px; /* Moves 20px down from its normal position */
background-color: green;
}
/* Absolute */
.absolute-container {
position: relative; /* This positions container to anchor absolute child */
width: 200px;
height: 200px;
background-color: lightgray;
margin: 20px 0;
}
.absolute-box {
position: absolute;
top: 10px;
left: 10px;
background-color: blue;
}
/* Fixed */
.fixed-box {
position: fixed;
top: 10px;
right: 10px;
background-color: red;
}
/* Sticky */
.sticky-box {
position: sticky;
top: 0; /* Sticks to the top of the viewport when scrolling reaches this point */
background-color: orange;
}
</style>
</head>
<body>
<div class="box static-box">Static</div>
<div class="box relative-box">Relative</div>
<div class="absolute-container">
<div class="box absolute-box">Absolute</div>
</div>
<div class="box fixed-box"<>/span>Fixed</div>
<div class="box sticky-box">Sticky</div>
<p>Scroll down to see how the sticky element behaves when scrolling.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur non diam nisl...</p>
<p>More content...</p>
<p>More content...</p>
<p>More content...</p>
<p>More content...</p>
<p>More content...</p>
<p>More content...</p>
<p>More content...</p>
<p>More content...</p>
<p>More content...</p>
<p>More content...</p>
<p>More content...</p>
<p>More content...</p>
<p>More content...</p>
<p>More content...</p>
<p>More content...</p>
<p>More content...</p>
<p>More content...</p>
</body>
</html>
CSS Z-index
The z-index property in CSS controls the stacking order of positioned elements along the z-axis (depth). Elements with a higher z-index value appear above those with lower values when they overlap.
Key Points About z-index
- Works with Positioned Elements: z-index only applies to elements that have a position value of relative, absolute, fixed, or sticky. It won’t work on elements with position: static;.
- Higher Values on Top: Elements with higher z-index values will appear above elements with lower values.
- Negative Values: z-index can take negative values, which will place the element below others with a higher z-index. Syntax
- Red Box (box1): z-index: 1; - Positioned at the lowest layer.
- Green Box (box2): z-index: 2; - Stacks above the red box.
- Blue Box (box3): z-index: 3; - Stacks above both the red and green boxes.
.element {
position: relative; /* Must be positioned to use z-index */
z-index: 10;
}
Example:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Z-Index Example</title>
<style>
/* Base styling for all boxes */
.box {
width: 100px;
height: 100px;
position: absolute;
color: white;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
}
/* Different z-index values */
.box1 {
background-color: red;
top: 50px;
left: 50px;
z-index: 1;
}
.box2 {
background-color: green;
top: 80px;
left: 80px;
z-index: 2;
}
.box3 {
background-color: blue;
top: 110px;
left: 110px;
z-index: 3;
}
</style>
</head>
<body>
<div class="box box1">Z-Index 1</div>
<div class="box box2">Z-Index 2</div>
<div class="box box3">Z-Index 3</div>
</body>
</html>
Explanation:
CSS Overflow
The CSS overflow property specifies how content is handled when it overflows the dimensions of its container. It determines whether to clip, hide, or provide scrollbars for overflowing content.
Syntax
element {
overflow: visible | hidden | scroll | auto | inherit;
}
Values of overflow:-
- visible (Default):
- Content overflows the container and is visible outside its boundaries.
- No clipping is applied.
- hidden:
- Content that overflows the container is clipped and not visible.
- No scrollbars are provided.
- scroll:
- Scrollbars are added, allowing users to scroll through the overflowing content, even if the content fits within the container.
- auto:
- Scrollbars appear only when the content overflows.
- If the content fits, no scrollbars are displayed.
- inherit:
- The element inherits the overflow value from its parent.
.box {
width: 100px;
height: 100px;
overflow: visible;
}
.box {
width: 100px;
height: 100px;
overflow: hidden;
}
.box {
width: 100px;
height: 100px;
overflow: scroll;
}
.box {
width: 100px;
height: 100px;
overflow: auto;
}
.box {
overflow: inherit;
}
Additional Overflow Properties:-
- overflow-x: Controls the horizontal overflow (visible, hidden, scroll, or auto).
- overflow-y: Controls the vertical overflow (visible, hidden, scroll, or auto).
- overflow: clip (Newer):
- Content is clipped, and no scrollbars are provided, similar to hidden, but it doesn’t allow scrolling even programmatically.
.box {
overflow-x: scroll;
}
.box {
overflow-y: hidden;
}
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Overflow Example</title>
<style>
.container {
width: 200px;
height: 100px;
border: 2px solid black;
margin: 20px auto;
padding: 10px;
font-size: 14px;
}
/* Overflow visible */
.visible {
overflow: visible;
background-color: lightblue;
}
/* Overflow hidden */
.hidden {
overflow: hidden;
background-color: lightgreen;
}
/* Overflow scroll */
.scroll {
overflow: scroll;
background-color: lightpink;
}
/* Overflow auto */
.auto {
overflow: auto;
background-color: lightyellow;
}
</style>
</head>
<body>
<h2>CSS Overflow Example</h2>
<p>Note: You have to add the more content in div box, you get more clarification on that.</p>
<div class="container visible">
<strong>Overflow: visible</strong><br>
This content will overflow the box and remain visible outside of it.
</div>
<div class="container hidden">
<strong>Overflow: hidden</strong><br>
This content will overflow the box but will be clipped, so you won't see it outside the box.
</div>
<div class="container scroll">
<strong>Overflow: scroll</strong><br>
This content will overflow the box and scrollbars will appear. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin bibendum.
</div>
<div class="container auto">
<strong>Overflow: auto</strong><br>
This content will show scrollbars only if it overflows. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin bibendum.
</div>
</body>
</html>
Overflow Table:
CSS Float
The float property in CSS is used to position an element to the left or right of its container, allowing other elements to wrap around it.
Syntax:
element {
float: left | right | none | inherit;
}
Values of float
- left:
- The element is floated to the left of its container.
- Content flows to the right of the floated element.
- right:
- The element is floated to the right of its container.
- Content flows to the left of the floated element.
- none (Default):
- The element is not floated and behaves as a block element in normal document flow.
- inherit:
- The element inherits the float value from its parent.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Float Example</title>
<style>
.container {
width: 100%;
background-color: lightgray;
}
.box {
width: 100px;
height: 100px;
margin: 10px;
color: white;
text-align: center;
line-height: 100px;
}
.left {
float: left;
background-color: blue;
}
.right {
float: right;
background-color: green;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
</style>
</head>
<body>
<h2>CSS Float Example</h2>
<div class="container clearfix">
<div class="box left">Left Float</div>
<div class="box right">Right Float</div>
<div class="box" style="background-color: red;">No Float</div>
</div>
<p>This text wraps around the floated elements above.</p>
</body>
</html>
Explanation
- Left Float: The blue box is floated to the left; subsequent content wraps to its right.
- Right Float: The green box is floated to the right; subsequent content wraps to its left.
- No Float: The red box stays in the normal document flow.
- Clearfix: The clearfix ensures the parent container (.container) encompasses the floated elements.
CSS clear Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Clear Example</title>
<style>
.container {
width: 100%;
}
.box {
width: 150px;
height: 100px;
margin: 10px;
color: white;
text-align: center;
line-height: 100px;
}
.left {
float: left;
background-color: blue;
}
.right {
float: right;
background-color: green;
}
.clear-both {
clear: both; /* Ensures this element is moved below both floats */
background-color: lightgray;
text-align: center;
padding: 10px;
}
</style>
</head>
<body>
<h2>CSS Clear Example</h2>
<div class="container">
<div class="box left">Left Float</div>
<div class="box right">Right Float</div>
<div class="clear-both">Cleared Below Both</div>
</div>
</body>
</html>
CSS clearfix
When elements inside a container are floated, the container's height might collapse because floated elements are removed from the normal document flow. The clearfix technique ensures the container includes its floated children.
CSS clearfix Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Clearfix Example</title>
<style>
.container {
width: 100%;
background-color: lightgray;
overflow: hidden; /* Modern browsers support this as a clearfix */
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
.box {
width: 150px;
height: 100px;
float: left;
margin: 10px;
color: white;
text-align: center;
line-height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<h2>CSS Clearfix Example</h2>
<div class="container clearfix">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</div>
</body>
</html>
When to Use Clear or Clearfix
- clear:
- Use it when you want a specific element to avoid overlapping with floated elements.
- For example, a footer below floated content.
- clearfix:
- Use it when you want a parent container to properly include floated child elements.
- Commonly used in layouts with floated grid systems or floated navigation menus.
Key Differences
Both are essential for managing layouts with floated elements effectively.
CSS inline-block
The display property in CSS determines how an element is visually displayed in the document. Three common values are block, inline, and inline-block.
- display: block
- Behavior: The element is a block-level element.
- Characteristics:
- Starts on a new line.
- Takes up the full width available by default.
- You can set width, height, margin, and padding.
- Examples: <div>, <p>, <section>, <header>, <footer>.
- display: inline
- Behavior: The element is inline.
- Characteristics:
- Does not start on a new line.
- Takes up only as much width as needed (content width).
- Does not allow setting width or height.
- Respects margin and padding, but only horizontally.
- Examples: <span>, <a>, <strong>, <em>.
- display: inline-block
- Behavior: A combination of inline and block behaviors.
- Characteristics:
- Does not start on a new line (like inline).
- Allows setting width, height, margin, and padding (like block).
- Sits inline with other elements but behaves like a block.
- Examples: Custom buttons, small boxes, aligned icons.
- Block: Use for structuring layouts or containers.
- Inline: Use for styling text or small inline elements.
- Inline-Block: Use for elements that need to be inline but have block-like properties (e.g., custom buttons, badges, etc.).
Examples
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Display: block | inline | inline-block</title>
<style>
.block {
display: block;
background-color: lightblue;
margin: 10px 0;
padding: 10px;
}
.inline {
display: inline;
background-color: lightgreen;
margin: 5px;
padding: 5px;
}
.inline-block {
display: inline-block;
width: 100px;
height: 50px;
background-color: lightcoral;
margin: 5px;
text-align: center;
line-height: 50px;
}
</style>
</head>
<body>
<h2>Display: block</h2>
<div class="block">I am block</div>
<div class="block">I also start on a new line</div>
<h2>Display: inline</h2>
<span class="inline">Inline 1</span>
<span class="inline">Inline 2</span>
<h2>Display: inline-block</h2>
<div class="inline-block">Box 1</div>
<div class="inline-block">Box 2</div>
</body>
</html>
When to Use
CSS Horizontal Align
- Align Elements Using Float
- Align Elements Using Position
- Align Text and Images Using Float and Clearfix Hack
- Clearfix Hack
You can use float to align elements horizontally. For floating elements, ensure to clear the float using the clearfix hack or other clearing methods.
Using position: absolute with left and right values allows precise horizontal alignment.
For aligning images and text horizontally, use float combined with clearfix.
The clearfix hack ensures that floating elements don’t cause their container to collapse. Add the following reusable CSS to clear floats:
.clearfix::after {
content: "";
display: table;
clear: both;
}
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Horizontal Alignment Example</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
/* 1. Horizontal Align Using Float */
.float-container {
border: 1px solid lightblue;
margin-bottom: 20px;
}
.float-left {
float: left;
width: 40%;
background-color: lightblue;
text-align: center;
padding: 10px;
}
.float-right {
float: right;
width: 40%;
background-color: lightcoral;
text-align: center;
padding: 10px;
}
/* Clearfix Hack */
.clearfix::after {
content: "";
display: table;
clear: both;
}
/* 2. Horizontal Align Using Position */
.position-container {
position: relative;
height: 100px;
border: 1px solid lightgreen;
margin-bottom: 20px;
}
.position-left {
position: absolute;
left: 0;
background-color: lightgreen;
padding: 10px;
}
.position-right {
position: absolute;
right: 0;
background-color: lightyellow;
padding: 10px;
}
/* Text and Image Alignment */
.text-image-container {
border: 1px solid lightgray;
margin-bottom: 20px;
}
.image {
float: left;
margin-right: 10px;
width: 100px;
height: 100px;
}
.text {
overflow: hidden; /* Ensures text wraps properly around the floated image */
padding: 10px;
}
</style>
</head>
<body>
<>CSS Horizontal Alignment</h1>
<!-- 1. Horizontal Align Using Float -->
<div class="float-container clearfix">
<div class="float-left">Left Aligned (Float)</div>
<div class="float-right">Right Aligned (Float)</div>
</div>
<!-- 2. Horizontal Align Using Position -->
<div class="position-container">
<div class="position-left">Left Aligned (Position)</div>
<div class="position-right">Right Aligned (Position)</div>
</div>
<!-- 3. Horizontal Align Text and Image -->
<div class="text-image-container clearfix">
<img src="https://via.placeholder.com/100" class="image" alt="Sample Image">
<div class="text">
<h2>Aligned Text</h2>
<p>
This is an example of text aligned horizontally with an image. The image is floated to the left, and the text wraps neatly around it.
</p>
</div>
</div>
</body>
</html>
Output
CSS Vertical Align
- Vertical Align Using line-height (Single Line Text)
- Vertical Align Using Padding
- Vertical Align Using position and transform
- Vertical Align Using Flexbox
This method is ideal for single-line text, where the line height is set to match the height of the container.
Using equal padding at the top and bottom to center content.
This method centers an element vertically regardless of its size.
Flexbox provides an efficient way to center content vertically and horizontally.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Vertical Alignment Example</title>
<style>
/* 1. Vertical Align Using Line-Height */
.line-height-container {
height: 100px;
line-height: 100px; /* Matches the height of the container */
text-align: center;
border: 1px solid lightblue;
margin-bottom: 20px;
}
/* 2. Vertical Align Using Padding */
.padding-container {
height: 100px;
padding: 25px 0; /* Equal top and bottom padding */
text-align: center;
border: 1px solid lightgreen;
margin-bottom: 20px;
}
/* 3. Vertical Align Using Position and Transform */
.position-container {
position: relative;
height: 100px;
border: 1px solid lightcoral;
margin-bottom: 20px;
}
.position-centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* Centers both vertically and horizontally */
background-color: lightcoral;
padding: 5px 10px;
color: white;
}
/* 4. Vertical Align Using Flexbox */
.flex-container {
display: flex;
justify-content: center; /* Centers horizontally */
align-items: center; /* Centers vertically */
height: 100px;
border: 1px solid lightyellow;
background-color: lightyellow;
}
</style>
</head>
<body>
<h1>CSS Vertical Align Techniques</h1>
<!-- 1. Using Line-Height -->
<div class="line-height-container">Centered with Line-Height</div>
<!-- 2. Using Padding -->
<div class="padding-container">Centered with Padding</div>
<!-- 3. Using Position and Transform -->
<div class="position-container">
<div class="position-centered">Centered with Position</div>
</div>
<!-- 4. Using Flexbox -->
<div class="flex-container">Centered with Flexbox</div>
</body>
</html>
Output
CSS Combinators
CSS combinators are selectors that explain the relationship between elements in an HTML document. There are four main combinators:
- Descendant Combinator ( - space)
- Selects all elements that are descendants of a specified element.
- Child Combinator (> - greater than)
- Selects elements that are direct children of a specified element.
- Adjacent Sibling Combinator (+ - plus)
- Selects an element that is directly next to a specified element (adjacent sibling).
- General Sibling Combinator (~ - tilde)
- Selects all elements that are siblings after a specified element.
Example
<style>
div p {
color: blue;
}
</style>
<div>
<p>This is a paragraph inside a div (blue).</p>
<span>
<p>This is another paragraph inside a span (blue).</p>
</span>
</div>
Example
<style>
div > p {
color: green;
}
</style>
<div>
<p>This is a direct child of div (green).</p>
<span>
<p>This is not a direct child of div (default).</p>
</span>
</div>
Example
<style>
h1 + p {
color: red;
}
</style>
<h1>Heading 1</h1>
<p>This paragraph is directly after h1 (red).</p>
<h1>Another Heading</h1>
<span>Not selected because it is not a p.</span>
Example
<style>
h1 ~ p {
color: orange;
}
</style>
<h1>Heading 1</h1>
<p>This paragraph is a sibling of h1 (orange).</p>
<p>This is also a sibling of h1 (orange).</p>
<span>This is a sibling but not a p (default).</span>
Complete Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Combinators</title>
<style>
/* Descendant */
div p {
color: blue;
}
/* Child */
div > p {
font-weight: bold;
}
/* Adjacent Sibling */
h1 + p {
font-style: italic;
}
/* General Sibling */
h1 ~ p {
text-decoration: underline;
}
</style>
</head>
<body>
<div>
<p>Descendant and Child (blue, bold).</p>
<span>
<p>Descendant only (blue).</p>
</span>
</div>
<h1>Heading</h1>
<p>Adjacent Sibling (italic, underlined).</p>
<p>General Sibling (underlined).</p>
</body>
</html>
Explanation
- Descendant: Targets all <p> inside a <div>.
- Child: Targets <p> that are direct children of <div>.
- Adjacent Sibling: Targets the first <p> immediately following an <h1>.
- General Sibling: Targets all <p> that are siblings of <h1> after it.
Combinators help build advanced and precise selectors in CSS.
CSS Pseudo-classes
Pseudo-classes are CSS selectors that apply styles to elements based on their state, position, or user interaction (e.g., :hover, :first-child). They enable dynamic and responsive styling without additional scripting.
Syntax of Pseudo-classes
selector:pseudo-class {
property: value;
}
Explanation:
- selector: The HTML element or CSS selector to which the pseudo-class is applied.
- pseudo-class: The specific pseudo-class (e.g., :hover, :nth-child(n)).
- property: value: The CSS properties and values to style the selected element.
Common CSS Pseudo-classes with Examples:
- :hover
- Purpose: Applied when the user hovers over an element (like a link or button).
- Effect: When the user hovers over the link, its color changes to red.
- :focus
- Purpose: Applied when an element (like an input field) gains focus (e.g., clicked or tabbed into).
- Effect: When the input field is focused, its background color changes to light yellow.
- :active
- Purpose: Applied when an element is being clicked (activated).
- Effect: When the button is clicked, its background color changes to green.
- :first-child
- Purpose: Targets the first child element of a parent element.
- Effect: The first paragraph becomes bold.
- :nth-child(n)
- Purpose: Targets elements based on their position in the parent, e.g., every odd or even element, or a specific index.
- Effect: Every even-numbered list item will have a light gray background.
- :checked
- Purpose: Applied to checkboxes or radio buttons that are selected.
- Effect: When the checkbox is checked, it will have a green background.
- :not(selector)
- Purpose: Excludes elements that match a given selector.
- Effect: All div elements except the one with the class exclude will have a light blue background.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
a:hover {
color: red;
}
</style>
</head>
<body>
<a href="#">Hover over me!</a>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<style>
input:focus {
background-color: lightyellow;
}
</style>
</head>
<body>
<input type="text" placeholder="Focus on me">
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<style>
button:active {
background-color: green;
}
</style>
</head>
<body>
<button>Click me!</button>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<style>
p:first-child {
font-weight: bold;
}
</style>
</head>
<body>
<div>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<style>
li:nth-child(even) {
background-color: lightgray;
}
</style>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<style>
input:checked {
background-color: green;
}
</style>
</head>
<body>
<input type="checkbox" id="myCheckbox"> I am checked
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<style>
div:not(.exclude) {
background-color: lightblue;
}
</style>
</head>
<body>
<div>This div is not excluded.</div>
<div class="exclude">This div is excluded.</div>
</body>
</html>
CSS Pseudo-elements
CSS Pseudo-elements are used to style specific parts of an element, such as the first letter, first line, or content before/after the element. Common examples include ::before, ::after, and ::first-letter.
- ::before
- Purpose: Used to insert content before the actual content of an element.
- Effect: The text "Note: " will appear before the paragraph content.
- ::after
- Purpose: Used to insert content after the content of an element.
- Effect: The text " (End of paragraph)" will appear after the paragraph content.
- ::first-letter
- Purpose: Targets the first letter of an element and allows you to style it.
- Effect: The first letter of the paragraph will appear larger and in red.
- ::first-line
- Purpose: Targets the first line of text within an element and applies styles.
- Effect: The first line of the paragraph will be bold and uppercase.
- ::selection
- Purpose: Styles the part of an element that the user selects (highlighted text).
- Effect: When the user highlights text, it will have a yellow background and black text color.
- ::marker
- Purpose: The ::marker pseudo-element is used to style the marker (e.g., bullet points or numbers) of a list item (<li>). It allows you to change the appearance of the list item markers without altering the HTML structure.
- ul { list-style-type: none; }: Removes the default bullet points from the list.
- li::marker: Targets the marker (bullet) of the list items.
- content: "★";: Replaces the default bullet with a star character.
- color: red;: Changes the color of the bullet to red.
- font-size: 20px;: Increases the size of the bullet.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
p::before {
content: "Note: ";
font-weight: bold;
}
</style>
</head>
<body>
<p>This is a paragraph with a pseudo-element before it.</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<style>
p::after {
content: " (End of paragraph)";
font-style: italic;
}
</style>
</head>
<body>
<p>This is a paragraph with a pseudo-element after it.</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<style>
p::first-letter {
font-size: 2em;
color: red;
}
</style>
</head>
<body>
<p>This paragraph has a large, red first letter.</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<style>
p::first-line {
font-weight: bold;
text-transform: uppercase;
}
</style>
</head>
<body>
<p>This is a paragraph where the first line will be bold and uppercase.</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<style>
::selection {
background-color: yellow;
color: black;
}
</style>
</head>
<body>
<p>Try selecting some text in this paragraph to see the effect.</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Pseudo-element ::marker Example</title>
<style>
ul {
list-style-type: none; /* Removes the default bullet points */
}
li::marker {
content: "★"; /* Replaces the default bullet with a star */
color: red; /* Changes the color of the bullet */
font-size: 20px; /* Makes the bullet bigger */
}
</style>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
</body>
</html>
Explanation:
Result
The list will have custom red star bullets instead of the default circular ones.
CSS Opacity
The opacity property in CSS is used to control the transparency of an element, making it partially or fully visible. It accepts values between 0 (completely transparent) and 1 (completely opaque).
Syntax
selector {
opacity: value;
}
- value: A number between 0 (fully transparent) and 1 (fully visible).
Syntax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Opacity Example</title>
<style>
.opaque {
opacity: 1; /* Fully visible */
}
.semi-transparent {
opacity: 0.5; /* 50% transparent */
}
.invisible {
opacity: 0; /* Fully transparent */
}
.titlewidth{
background: red;
opacity: 1;
}
</style>
</head>
<body>
<h2>Using opacity: 1</h2>
<div class="opaque titlewidth">This is fully visible (opacity: 1).</div>
<h2>Using opacity: 0.5</h2>
<div class="semi-transparent titlewidth">This is semi-transparent (opacity: 0.5).</div>
<h2>Using opacity: 0</h2>
<div class="invisible titlewidth">This is invisible (opacity: 0).</div>
</body>
</html>
Hover Effect Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Opacity Hover Example</title>
<style>
.hover-effect1 {
opacity: 0.8; /* Default transparency */
transition: opacity 0.3s ease; /* Smooth transition */
}
.hover-effect1:hover {
opacity: 1; /* Fully visible on hover */
}
.hover-effect2 {
opacity: 0.5; /* Default transparency */
transition: opacity 0.3s ease; /* Smooth transition */
}
.hover-effect2:hover {
opacity: 1; /* Fully visible on hover */
}
.hover-effect3 {
opacity: 0.2; /* Default transparency */
transition: opacity 0.3s ease; /* Smooth transition */
}
.hover-effect3:hover {
opacity: 1; /* Fully visible on hover */
}
.positions{
display: flex;
justify-content: space-around;
}
h2{
width: 210px;
height: 150px;
}
</style>
</head>
<body>
<div class="positions">
<div><
<h2>Default transparency is 0.8 and Fully visible on hover Opacity is 1</h2>
<img class="hover-effect1" src="https://cdn.shopify.com/s/files/1/0302/4551/9492/files/2150797010.jpg?v=1714126223" alt="Hover to see full opacity" width="200">
</div>
<div>
<h2>Default transparency is 0.5 and Fully visible on hover Opacity is 1</h2>
<img class="hover-effect2" src="https://cdn.shopify.com/s/files/1/0302/4551/9492/files/2150797010.jpg?v=1714126223" alt="Hover to see full opacity" width="200">
</div>
<div>
<h2>Default transparency is 0.2 and Fully visible on hover Opacity is 1</h2>
<img class="hover-effect3" src="https://cdn.shopify.com/s/files/1/0302/4551/9492/files/2150797010.jpg?v=1714126223" alt="Hover to see full opacity" width="200">
</div>
</div>
</body>
</html>
CSS Navigation
Navigation bars in CSS are styled menus that help users navigate through different sections of a website. They are typically created using lists (<ul> and <li>) and styled with CSS to display links horizontally or vertically. Common styles include hover effects, dropdowns, and responsive layouts using flexbox or grid. Navigation bars improve usability and enhance the visual appeal of a website.
Types:
- Horizontal Navigation
- Vertical Navigation
- Dropdown Navigation
- Sidebar Navigation
- Tabbed Navigation
CSS Horizontal Navigation
- Description: Menu items are displayed in a row, horizontally.
- Use Case: Commonly used for main website menus.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Horizontal Navigation</title>
<style>
.nav-horizontal {
list-style: none;
display: flex;
padding: 0;
}
.nav-horizontal li {
margin-right: 20px;
font-size: 20px;
}
.nav-horizontal a {
text-decoration: none;
color: blue;
}
</style>
</head>
<body>
<ul class="nav-horizontal">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</body>
</html>
CSS Vertical Navigation
- Description: Menu items are displayed in a column, vertically.
- Use Case: Used for sidebars or dropdown menus.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Vertical Navigation</title>
<style>
.nav-vertical {
list-style: none;
padding: 0;
}
.nav-vertical li {
margin-bottom: 10px;
}
.nav-vertical a {
text-decoration: none;
color: green;
}
</style>
</head>
<body>
<ul class="nav-vertical">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</body>
</html>
CSS Dropdown Navigation
- Description: Nested menu items appear when hovering over a parent item.
- Use Case: Used for multi-level navigation.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Dropdown Navigation</title>
<style>
/* Basic styling for navigation */
nav {
background-color: #333;
padding: 10px;
}
nav ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
}
nav ul li {
position: relative; /* Required for dropdown positioning */
margin-right: 20px;
}
nav ul li a {
text-decoration: none;
color: white;
padding: 10px 15px;
display: block;
}
nav ul li a:hover {
background-color: #575757;
}
/* Dropdown menu styles */
.dropdown {
display: none;
position: absolute;
top: 100%; /* Position below the parent menu item */
left: 0;
background-color: #444;
list-style: none;
padding: 0;
}
.dropdown li a {
padding: 10px 15px;
}
.dropdown li a:hover {
background-color: #575757;
color: black;
}
/* Show dropdown on hover */
nav ul li:hover .dropdown {
display: block;
}
</style>
</head>
<body>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li>
<a href="#">Services</a>
<ul class="dropdown">
<li><a href="#">Web Development</a></li>
<li><a href="#">App Development</a></li>
<li><a href="#">SEO</a></li>
<li><a href="#">Digital Marketing</a></li>
</ul>
</li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</body>
<