Basics of CSS


Topics :-
Selectors
Pseudo Elements
Margin and Padding
Border and its properties
Background and its properties
Height and Width
Selectors :
Selectors are the things similar to that of patterns which are used for handling and applying styles to specific HTML elements. And these are the things used to determine which elements should be affected by CSS rules and regulations.
Generally there are many selectors but we consider only few which are mainly used. They are,
Universal Selector :-
The universal selector in CSS is a powerful and versatile tool that allows you to select all elements on a webpage. Represented by an asterisk (*), it applies styles to every element within the scope of your CSS, making it particularly useful when you want to apply a global style or reset all elements to a consistent baseline.
htm<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Universal Selector Example</title> </head> <body> <h1>Universal Selector Example</h1> <p>This paragraph inherits the universal selector styles.</p> </body> </html>
*{ margin: 0; padding: 0; box-sizing: border-box; font-family: Arial, sans-serif; } body { background-color: lightgray; text-align: center; padding: 20px; } h1 { color: darkblue; } p { color: darkred; font-size: 18px; }
Common Use Cases for the Universal Selector :-
CSS Reset: The universal selector is frequently used to reset margins, paddings, or borders across all elements. This ensures that every browser starts with a consistent baseline, eliminating the default styles that can vary between browsers.
Global Styling: If you want to apply a specific style, such as a font family or background color, to all elements on the page, the universal selector can achieve this in one line.
Debugging: Developers sometimes use the universal selector to quickly apply a temporary style to all elements for debugging purposes, making it easier to identify layout issues.
Scoped Styling: By combining the universal selector with other selectors, such as child or descendant selectors, you can apply styles selectively to specific areas of your webpage.
Things to Keep in Mind :-
While the universal selector is incredibly useful, it should be used with caution. Overusing it can lead to performance issues, especially on large or complex web pages, as it applies styles to every single element. Additionally, it may inadvertently override more specific styles, so always ensure you test thoroughly when using it.
By understanding the universal selector and its applications, you can create cleaner, more efficient CSS and streamline your web development process. Whether you’re resetting styles, applying global changes, or debugging, this selector is a handy tool to have in your CSS toolkit.
Individual Selector :-
Individual Selector performs operations directly with the name, on only one thing that is being targeted or selected.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ID Selector Example</title> <link rel="stylesheet" href="styles.css"> <!-- Linking external CSS file --> </head> <body> <div ="uniqueElement">This is a uniquely styled div.</div> <p>Hi, There!</p> </body> </html>
/* ID Selector */ div { color: white; background-color: blue; padding: 10px; font-size: 18px; text-align: center; border-radius: 5px; } p { color: white; background-color: blue; padding: 10px; font-size: 18px; }
Class & ID Selector :-
In CSS, selectors are used to target HTML elements and apply styles to them. Among the most commonly used selectors are the class and ID selectors. Understanding the difference between these two and knowing when to use each is crucial for writing clean and efficient CSS.
Class Selector (
.
) :<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Class Selector</title> <link rel="stylesheet" href="styles.css"> <!-- Linking external CSS file --> </head> <body> <p class="highlight">This is a highlighted paragraph.</p> <p>This is a normal paragraph.</p> </body> </html>
/* Class Selector */ .highlight { color: white; background-color: blue; padding: 10px; border-radius: 5px; }
ID Selector (
#
) :<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS ID Selector</title> <link rel="stylesheet" href="styles.css"> <!-- Linking external CSS file --> </head> <body> <p id="unique">This paragraph has a unique ID.</p> <p>This is a normal paragraph.</p> </body> </html>
cssCopyEdit/* ID Selector */ #unique { color: white; background-color: green; padding: 10px; border-radius: 5px; }
Key Differences Between Class and ID Selectors :-
Reusability: Classes can be applied to multiple elements, whereas IDs are unique and should only be used for one element.
Specificity: ID selectors have higher specificity than class selectors, meaning they will override class styles if both are applied to the same element.
Purpose: Classes are typically used for grouping and styling multiple elements, while IDs are reserved for single, unique elements.
Best Practices :-
Use class selectors for general styling and when you need to apply the same styles to multiple elements.
Reserve ID selectors for unique elements that require distinct styling or for elements you need to target specifically in JavaScript.
Avoid overusing IDs in CSS, as it can make your styles harder to maintain and debug.
Keep your naming conventions clear and meaningful to improve code readability.
By effectively using class and ID selectors, you can create well-structured and maintainable CSS that enhances the overall design and functionality of your website. Understanding their differences and applying them judiciously will help you write cleaner and more efficient code.
And Selector (Chained) :-
In CSS, the "And Selector" is often referred to as a "chained selector." This technique allows developers to apply styles to elements that meet multiple criteria. By combining multiple selectors, you can target elements more specifically and create highly refined styling rules for your web pages.
Let's say we want to style a
<button>
element that has both.primary
and.rounded
classes.<button class="primary rounded">Click Me</button> <button class="primary">Primary Button</button> <button class="rounded">Rounded Button</button>
/* This applies only to elements that have BOTH 'primary' and 'rounded' classes */ .primary.rounded { background-color: blue; color: white; border-radius: 10px; padding: 10px 20px; border: none; }
In summary, chained selectors in CSS are a powerful tool for creating targeted styles. By combining multiple selectors, you can ensure your styles are applied only to the elements you intend, resulting in a more organized and efficient stylesheet.
Combined Selector :-
A combined selector in CSS refers to using multiple selectors together to target specific elements more precisely. Some common types include:
Group Selector (
,
) :Applies styles to multiple elements.
h1, p, div { font-family: Arial, sans-serif; }
<h1>Heading</h1> <p>Paragraph text</p> <div>Div content</div>
A combined selector is a method used in styling or querying elements that allows you to target multiple elements or specific combinations of elements at once. It typically involves chaining or grouping selectors to apply styles or actions efficiently. This approach enhances flexibility and reduces redundancy in design or programming by enabling more concise and organized rules.
Inside an Element :-
When styling elements inside another element in CSS, you can use descendant selectors or child selectors to target specific nested elements. For example, if you want to style all paragraphs inside a div, you would use a selector like
div p
. Similarly, if you want to style only the direct children of a container, you would use the child combinator>
likediv > p
. You can also combine these with classes, IDs, or pseudo-classes for more precise targeting. This approach helps maintain a clean and organized structure in your CSS, ensuring styles are applied to the correct elements.div ul li{ /* enter your styling here... */ }
Direct Child :-
In web development, the term "direct child" refers to an element that is immediately nested within a parent element in the Document Object Model (DOM) hierarchy. This concept is crucial when working with HTML and CSS, as it allows developers to target specific elements with precision.
For example, in an HTML structure, if you have a
<div>
element containing multiple child elements, only those elements directly inside the<div>
are considered direct children. Any elements nested further within those children are not classified as direct children but rather as descendants.div > li{ /* Enter your styling here where targeted elements are li...*/ }
Why is the Direct Child Concept Important?
Precise Styling with CSS: The
>
combinator in CSS is used to apply styles specifically to direct children of an element. This ensures that only the immediate children are affected, leaving deeper nested descendants untouched. For instance:div > p { color: blue; }
In this example, only
<p>
elements that are direct children of a<div>
will have blue text.Efficient DOM Manipulation: In JavaScript, understanding the direct child relationship can help you navigate and manipulate the DOM effectively. Methods like
parentElement
andchildren
allow you to access parent and child elements directly, streamlining your code.Improved Accessibility: Structuring your HTML with clear parent-child relationships enhances the accessibility of your website. Screen readers and other assistive technologies rely on well-defined hierarchies to provide users with a seamless experience.
Common Use Cases for Direct Children
Designing Layouts: When creating grid or flexbox layouts, targeting direct children ensures that only the intended elements are styled or positioned.
Event Delegation: In JavaScript, you can attach event listeners to a parent element and use the direct child relationship to identify which child triggered the event.
Component-Based Development: In frameworks like React or Vue, understanding how components render direct children helps in structuring reusable and maintainable code.
Tips for Working with Direct Children
Use clear and semantic HTML to make parent-child relationships intuitive.
Leverage browser developer tools to inspect and debug DOM hierarchies.
Combine the direct child selector with classes or IDs for more granular control over styling and scripting.
In conclusion, mastering the concept of direct children is a fundamental skill for web developers. Whether you're styling elements, writing scripts, or building complex web applications, understanding this relationship will help you write cleaner, more efficient code.
Sibling (-) or (+) in CSS :-
In CSS, sibling combinators are powerful tools that allow you to target elements based on their relationship with other elements in the document. These combinators are particularly useful for styling elements dynamically without adding extra classes or IDs to your HTML structure. There are two main types of sibling combinators in CSS: the adjacent sibling combinator (+
) and the general sibling combinator (~
).
Adjacent Sibling Combinator (+
) :-
The adjacent sibling combinator is used to select an element that is immediately preceded by a specified element. This means the two elements must share the same parent, and the targeted element must come directly after the specified element in the DOM.
For example, if you want to style a paragraph (<p>
) that comes immediately after a heading (<h1>
), you can use the +
combinator. This is particularly useful when you want to apply specific styles to elements that follow a certain structure.
General Sibling Combinator (~
) :-
The general sibling combinator is a bit more flexible. It selects all elements that are siblings of a specified element, regardless of whether they are immediately adjacent or not. As long as the elements share the same parent and appear after the specified element in the DOM, they will be affected by the styles.
This combinator is helpful for applying styles to multiple sibling elements without worrying about their exact position relative to the specified element.
Adjacent Sibling Selector (+
) :-
- Selects the immediate next sibling.
h1 + p {
color: green;
}
<h1>Heading</h1>
<p>This paragraph after h1 will be green.</p>
General Sibling Selector (~
) :-
- Selects all siblings after a specified element.
h1 ~ p {
color: orange;
}
<h1>Heading</h1>
<p>This paragraph will be orange.</p>
<p>This one too!</p>
When to Use Each
Use the
+
combinator when you need to target a single, specific sibling element that directly follows another element.Use the
~
combinator when you want to target multiple sibling elements that appear after a specified element.
By understanding and leveraging these sibling combinators effectively, you can write cleaner, more efficient CSS that adapts dynamically to your HTML structure.
Pseudo Elements in css:
Pseudo-elements in CSS are powerful tools that allow developers to style specific parts of an element without requiring additional HTML markup. They are especially useful for adding decorative elements or enhancing the appearance of a webpage without cluttering the DOM structure. By using pseudo-elements, you can achieve creative and dynamic designs with minimal effort.
Pseudo-elements are denoted by a double colon (::) followed by the name of the pseudo-element. Some of the most commonly used pseudo-elements include ::before
, ::after
, ::first-letter
, and ::first-line
. Each serves a unique purpose and can be utilized to target specific portions of content within an element.
For example, the ::before
and ::after
pseudo-elements allow you to insert content before or after an element's actual content. This is particularly useful for adding icons, decorative lines, or other visual enhancements without modifying the HTML. Similarly, the ::first-letter
pseudo-element enables you to style the first letter of a paragraph, often used in magazine-style layouts to create a drop cap effect. The ::first-line
pseudo-element, on the other hand, allows you to style the first line of text within a block of content, making it stand out.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pseudo Elements Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>This is an example paragraph to demonstrate CSS pseudo-elements.</p>
</body>
</html>
: : before :-
/* Adds content before the paragraph */
p::before {
content: "***";
color: red;
font-weight: bold;
}
: : after :-
/* Adds content after the paragraph */
p::after {
content: " $$$";
color: green;
font-weight: bold;
}
: :first-letter :-
/* Styles the first letter */
p::first-letter {
font-size: 2em;
color: blue;
}
: : first-line :-
/* Styles the first line */
p::first-line {
font-weight: bold;
color: darkred;
}
: : selection :-
/* Styles the selected text */
::selection {
background: yellow;
color: black;
}
It's important to note that pseudo-elements are not standalone elements; they are part of the element they are applied to. As such, they inherit styles from their parent element unless explicitly overridden.
When working with pseudo-elements, remember that they require the content
property to function properly. Without defining content
, pseudo-elements like ::before
and ::after
will not render anything on the page. The content
property can be used to insert text, symbols, or even left empty for purely decorative purposes.
In conclusion, pseudo-elements in CSS are an essential tool for web designers and developers, offering a way to enhance the visual appeal and functionality of a webpage without overcomplicating the HTML structure. By mastering pseudo-elements, you can take your designs to the next level and create visually stunning interfaces with ease.
Margin and Padding :
In CSS, margin and padding are crucial for layout and spacing:
Margin: Creates space outside the element, pushing it away from neighboring elements. It does not affect the element's size.
Padding: Adds space inside the element, between its content and border. It increases the overall size of the element by expanding the area around its content.
Key Differences:
Margin affects the external spacing between elements, while padding impacts the internal spacing within an element.
Margins can collapse (merge) between adjacent elements, but padding does not collapse.
Using both effectively allows for precise control over layout and design, ensuring a visually balanced and user-friendly interface.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Margin and Padding Example</title>
<link rel="stylesheet" href="styles.css"> <!-- Linking external CSS file -->
</head>
<body>
<div class="box">This is a box</div>
</body>
</html>
Margin :-
.box {
width: 200px;
height: 100px;
background-color: lightblue;
border: 2px solid blue;
/* Margin - Space outside the border */
margin: 30px;
}
Padding :-
.box {
/* Padding - Space inside the border */
padding: 20px;
}
Explanation
padding: 20px;
→ Adds 20px of space inside the box around the content.margin: 30px;
→ Adds 30px of space outside the box, separating it from other elements.
Border and its properties :
Borders in CSS are used to define the outline of an element. They can be customized using various properties to achieve different styles and appearances. The key properties for borders in CSS include:
border-width :-
Specifies the thickness of the border. It can take values like thin, medium, thick, or a specific measurement (e.g., 2px, 0.5em).
border-style :-
Defines the style of the border. Common styles include solid, dashed, dotted, double, groove, ridge, inset, outset, and none.
border-color:
Sets the color of the border. You can use color names, HEX codes, RGB, RGBA, HSL, or HSLA values.
border-radius:
Rounds the corners of the border, creating a softer or circular appearance. It can take values in pixels, percentages, or other units.
border:
A shorthand property that combines border-width, border-style, and border-color in a single line.
border-top, border-right, border-bottom, border-left:
These properties allow you to style each side of the border individually.
border-image: Enables the use of an image as a border. It involves properties like border-image-source, border-image-slice, border-image-width, border-image-outset, and border-image-repeat
[Not that much efficient].
By combining these properties, you can create visually appealing borders that enhance the design and structure of your web pages.
Examples of Border Properties :-
Basic Border Example :-
.box1 { border: 2px solid red; }
<div class="box1">This is a bordered div</div>
Different Border Styles :-
.box2 { border: 3px dashed blue; } .box3 { border: 4px dotted green; } .box4 { border: 5px double purple; }
<div class="box2">Dashed Border</div> <div class="box3">Dotted Border</div> <div class="box4">Double Border</div>
Individual Border Sides :-
.box5 { border-top: 3px solid black; border-right: 4px dashed red; border-bottom: 5px double blue; border-left: 2px dotted green; }
<div class="box5">Different borders on each side</div>
Border Radius (Rounded Corners) :-
.box6 { border: 3px solid purple; border-radius: 10px; }
<div class="box6">Rounded Border</div>
Shorthand Border Property :-
.box7 {
border: 5px solid black;
}
<div class="box7">Shorthand Border</div>
Background and its properties :
In CSS, the background
property is used to set the background of an element. It is a shorthand property that allows you to set multiple background properties in a single declaration.
Background Properties in CSS
background-color
– Sets the background color of an element.background-image
– Sets an image as the background.background-repeat
– Controls if/how a background image repeats.background-position
– Sets the initial position of the background image.background-size
– Defines the size of the background image.background-attachment
– Determines whether the background image scrolls with the page or stays fixed.background-clip
– Defines how far the background should extend within an element.background-origin
– Specifies where the background image is positioned.background-blend-mode
– Specifies how the background image blends with the background color.background
(shorthand) – Combines.
body {
background-color: #f0f0f0; /* Light gray background */
background-image: url('background.jpg'); /* Adding a background image */
background-repeat: no-repeat; /* Prevent repeating */
background-position: center center; /* Centering the image */
background-size: cover; /* Cover the entire viewport */
background-attachment: fixed; /* Fixed background */
}
/* for background shorthand*/
body {
background: #f0f0f0 url('background.jpg') no-repeat center center / cover fixed;
}
Height and Width :
In CSS, the height
and width
properties define the dimensions of an element. These properties can be set using different units like pixels (px
), percentages (%
), viewport units (vw
, vh
), and more.
When working with CSS, understanding how to manage the height and width of elements is fundamental to creating responsive and visually appealing designs. The height and width properties are used to set the size of an element's content box, which directly affects the layout and structure of your webpage.
Heigh :-
The height
property specifies the vertical dimension of an element. You can define it in various units such as pixels (px), percentages (%), em, rem, viewport height (vh), and more. For example, setting a height in pixels gives a fixed size, while percentages allow for a more flexible design that adapts to the parent element.
When no height is explicitly defined, the height of an element is determined by its content. However, if you want to ensure consistency or limit the size, you can use the min-height
and max-height
properties. These allow you to set boundaries, ensuring the element doesn't shrink below or grow beyond certain limits.
Width :-
The width
property controls the horizontal dimension of an element. Like height, it can also be specified using various units. A fixed width in pixels ensures the element remains the same size regardless of the screen size, while a percentage-based width makes it responsive to the parent container.
The min-width
and max-width
properties are useful for creating adaptable layouts. For example, setting a min-width
can prevent an element from becoming too narrow on smaller screens, while a max-width
ensures it doesn’t stretch excessively.
Combining Height and Width :
Height and width often work hand-in-hand to define the overall size of an element. However, it’s important to consider the box model when setting these properties. The box model includes padding, borders, and margins, which can affect the total size of an element. To simplify this, you can use the box-sizing
property with the value border-box
, which ensures that padding and borders are included within the height and width you specify.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Height and Width</title>
<link rel="stylesheet" href="styles.css"> <!-- Linking external CSS -->
</head>
<body>
<div class="box">Fixed Box</div>
<br>
<div class="responsive-box">Responsive Box</div>
</body>
</html>
cssCopyEdit.box {
width: 200px; /* Fixed width */
height: 150px; /* Fixed height */
background-color: lightblue;
text-align: center;
line-height: 150px; /* Align text vertically */
border: 2px solid blue;
}
.responsive-box {
width: 50%; /* 50% of the parent container */
height: 20vh; /* 20% of the viewport height */
background-color: lightcoral;
text-align: center;
line-height: 20vh;
border: 2px solid red;
}
Explanation :-
.box
has a fixed width (200px
) and height (150px
).
.responsive-box
has a relative width (50%
of the parent) and height (20vh
, which is 20% of the viewport height).
Subscribe to my newsletter
Read articles from ABUBAKAR SIDDIQ SHAIK directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
