0% found this document useful (0 votes)
1 views

Web unit 3

Uploaded by

sangeethapriyads
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Web unit 3

Uploaded by

sangeethapriyads
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Introducing CSS (Cascading Style Sheets)

Introduction
Cascading Style Sheets (CSS) is a style sheet language used to describe the look and formatting of a
document written in a markup language like HTML. While HTML defines the structure and content
of a web page, CSS is responsible for its visual presentation. It allows web developers to separate
content from design, thus enhancing productivity, maintainability, and reusability of web documents.
CSS was developed by the World Wide Web Consortium (W3C) and has become a fundamental part
of modern web development. With CSS, designers can apply consistent styles to multiple web pages,
create responsive layouts, and improve accessibility.

Need for CSS


Before CSS, all the styling for web pages had to be written inline in HTML using tags like <font>,
<b>, and <center>. This approach made HTML files large, difficult to maintain, and not very flexible.
CSS was introduced to solve the following problems:
1. Separation of Content and Design:
HTML should define the structure, while CSS handles the design. This separation ensures that
content and layout can be modified independently.
2. Consistency Across Pages:
A single CSS file can be linked to multiple HTML documents, ensuring a uniform look and
feel across a website.
3. Reduced Code Duplication:
CSS eliminates the need to write repeated style declarations in every HTML file, reducing
redundancy and file size.
4. Improved Maintainability:
By updating just one CSS file, changes can be applied site-wide, making website maintenance
faster and more efficient.

Syntax of CSS
CSS uses a specific syntax to define style rules. Each rule consists of a selector and a declaration
block.
selector {
property: value;
property: value;
}
Example:
h1 {
color: blue;
font-size: 24px;
}
• Selector: Specifies the HTML element to be styled (e.g., h1, p, div).
• Property: A style attribute (e.g., color, font-size).
• Value: The value assigned to the property (e.g., blue, 24px).
Advantages of CSS
• Separation of structure and style
• Improved website performance
• Better accessibility and device compatibility
• Scalable for large web projects
• Enables animations and transitions

Where You Can Add CSS Rules

Introduction
CSS (Cascading Style Sheets) is a style sheet language used for describing the visual presentation of
HTML elements. It controls layout, colors, fonts, spacing, and overall design. To apply CSS to HTML
documents, rules must be added in specific locations, known as methods of CSS application. These
methods determine how styles are linked or embedded into a web page.
The three main methods for adding CSS rules are:
1. Inline CSS
2. Internal CSS
3. External CSS
Additionally, CSS can also be imported using the @import rule and media queries can apply CSS
conditionally. Understanding where to add CSS rules is fundamental for designing maintainable and
efficient web pages.

1. Inline CSS
Definition
Inline CSS involves adding CSS rules directly into the HTML element using the style attribute. It is
used to apply a unique style to a single element on the page.
Syntax
<tagname style="property: value;">Content</tagname>
Example
<p style="color: red; font-size: 18px;">This is a paragraph with inline styling.</p>
Use Cases
• Quick testing or temporary styling.
• Overriding other CSS rules for a specific element.
• Emails or embedded HTML where external files are restricted.
Advantages
• Easy to apply.
• Does not require an external or internal stylesheet.
• Style is immediately visible.
Disadvantages
• Not reusable.
• Leads to messy code.
• Difficult to maintain and debug.
• Reduces separation between content and design.

2. Internal CSS
Definition
Internal CSS is written within the <style> tag inside the <head> section of the HTML document. It
applies styles to the entire page.
Syntax
<head>
<style>
selector {
property: value;
}
</style>
</head>
Example
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: green;
text-align: center;
}
p{
font-size: 16px;
}
</style>
</head>
<body>
<h1>Welcome</h1>
<p>This is styled using internal CSS.</p>
</body>
</html>
Use Cases
• When styling is only required for a single page.
• For small projects or testing without external files.
• Rapid prototyping or personal websites.
Advantages
• Styles are centralized in one section of the document.
• Easier to maintain than inline CSS.
• Better separation than inline styles.
Disadvantages
• Styles not reusable across multiple pages.
• Increases page size.
• Difficult to manage for large projects.

3. External CSS
Definition
External CSS involves writing CSS rules in a separate .css file and linking it to an HTML document
using the <link> element in the <head>.
Syntax
HTML file:
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
style.css:
body {
background-color: #f9f9f9;
}
h1 {
color: blue;
}
Use Cases
• Large websites requiring a consistent look.
• Projects where styles need to be reused.
• Team collaboration and version control.
Advantages
• Clean and organized code.
• Styles can be reused across multiple pages.
• Better site performance with browser caching.
• Enhances collaboration and modularity.
Disadvantages
• Requires additional HTTP request.
• Changes are not immediately visible if CSS file fails to load.
• Not suitable for very small or single-page sites.

4. Using @import Rule


Definition
The @import rule allows you to import one CSS file into another. It is useful for breaking down CSS
into smaller, manageable files.
Syntax
@import url("main.css");
Example
style.css:
@import url("header.css");
@import url("footer.css");
body {
font-family: Arial;
}
Use Cases
• Organizing styles into multiple files.
• Loading themes or libraries (like Google Fonts).
• Overriding default styles.
Advantages
• Clean organization of styles.
• Enables modular design.
Disadvantages
• Slower performance due to multiple file loads.
• Imported styles must be loaded before other styles.

5. Media Queries (Conditional CSS)


Definition
Media queries are a way to apply CSS rules only when certain conditions are met, such as screen size
or device orientation.
Syntax
@media screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
Use Cases
• Responsive design.
• Styling for different devices (mobile, tablet, desktop).
• Accessibility adjustments.
Advantages
• Enhances user experience across devices.
• Eliminates need for multiple versions of the site.
Disadvantages
• Increases CSS complexity.
• Requires testing across various devices.

Comparison of CSS Rule Placement


Criteria Inline CSS Internal CSS External CSS

Reusability No No Yes

Maintainability Poor Moderate High

Code Cleanliness Poor Better Best

Performance Fastest Load Moderate Fast (cached)

Ideal for Single elements Single page Multi-page projects

Separation of Concerns No Partial Yes

Best Practices for Adding CSS


1. Use External CSS for Scalability:
For medium to large websites, using external CSS ensures consistency and maintainability.
2. Avoid Inline CSS for Styling:
Inline CSS should be limited to quick fixes or testing. It clutters HTML and reduces
flexibility.
3. Use Internal CSS for Specific Pages:
When styles are page-specific and not reused, internal CSS is acceptable.
4. Organize Using @import:
Break large stylesheets into multiple files using @import or SCSS includes.
5. Leverage Media Queries:
Responsive design should be implemented using media queries for better adaptability.

Practical Example
Let’s say you are building a website with a header, navigation menu, and a content section.
Using Inline CSS:
<h1 style="color: blue;">My Website</h1>
Using Internal CSS:
<style>
nav {
background-color: #333;
color: white;
}
</style>
Using External CSS (style.css):
header {
background-color: #f1f1f1;
padding: 20px;
text-align: center;
}
HTML Linking External CSS:
<link rel="stylesheet" href="style.css">

CSS Properties

Introduction
CSS (Cascading Style Sheets) is a language used to describe the presentation of HTML documents.
CSS properties are predefined keywords used to define how HTML elements should be displayed in a
web browser. Each property is paired with a value, and this combination forms a CSS rule.
The general syntax is:
selector {
property: value;
}
Example:
p{
color: blue;
font-size: 16px;
}
CSS properties control everything from text color, background, borders, margins, padding,
positioning, and more. Understanding various categories of CSS properties is essential for creating
visually appealing and well-structured web pages.

1. Text Properties
These properties are used to style text content inside HTML elements.
Important Text Properties

Property Description
color Sets the text color

font-size Sets the size of the text

font-family Sets the typeface

font-style Makes text italic

font-weight Sets text to bold

text-align Aligns the text (left, right, center)

text-decoration Adds underline, overline, line-through

letter-spacing Adjusts space between letters

line-height Sets height between lines

Example
h1 {
font-family: Arial;
font-size: 28px;
color: navy;
text-align: center;
}

2. Background Properties
Background properties allow control over an element’s background such as color, image, position, and
repetition.
Key Background Properties

Property Description

background-color Sets background color


background-image Sets a background image

background-repeat Repeats the image (x, y, both, none)


background-position Sets the position of the image

background-size Resizes the background image

background-attachment Fixes or scrolls background


Example
body {
background-color: #f0f0f0;
background-image: url("bg.jpg");
background-repeat: no-repeat;
background-position: center top;
background-size: cover;
}

3. Box Model Properties


Every HTML element is considered a box in CSS. The box model consists of margins, borders,
padding, and content.
Box Model Layers
1. Content – The actual text or image.
2. Padding – Space around the content.
3. Border – Line around padding.
4. Margin – Space outside the border.
Important Box Model Properties

Property Description

width Sets the width of an element

height Sets the height of an element


padding Adds space between content and border

margin Adds space outside the border


border Defines the boundary style

box-sizing Controls how total width/height is calculated

Example
div {
width: 300px;
height: 200px;
padding: 20px;
margin: 30px;
border: 2px solid black;
box-sizing: border-box;
}

4. Border Properties
CSS border properties define the width, style, and color of an element’s border.
Border Sub-Properties

Property Description

border-width Specifies the thickness

border-style Defines the type (solid, dotted, dashed)

border-color Specifies the color


border-radius Rounds the corners

Example
img {
border: 5px dashed red;
border-radius: 15px;
}

5. Margin and Padding Properties


Margin Properties
Margins create space outside the element’s border.
margin: 10px; /* all sides */
margin: 10px 20px; /* top-bottom, left-right */
margin: 10px 15px 5px 0px; /* top, right, bottom, left */
Padding Properties
Padding creates space between content and the border.
padding: 20px;
padding: 10px 15px;
padding: 5px 10px 15px 20px;

6. Display and Visibility Properties


These control the rendering of HTML elements.
Common Properties

Property Description

display Defines the display type (block, inline, flex, none)

visibility Controls visibility (visible, hidden)


overflow Handles overflowed content (visible, scroll, hidden, auto)

Example
div {
display: none; /* element not shown */
}
span {
display: inline;
}

7. Positioning Properties
CSS provides several positioning schemes for arranging elements.
Position Values

Value Description
static Default, normal flow

relative Relative to its normal position


absolute Relative to the nearest positioned ancestor

fixed Relative to the browser window


sticky Switches between relative and fixed

Supporting Properties
• top, right, bottom, left
• z-index
Example
#menu {
position: fixed;
top: 0;
width: 100%;
background-color: black;
color: white;
}

8. Flexbox Properties
Flexbox layout simplifies alignment and distribution of space among items in a container.
Key Flexbox Properties

Property Description

display: flex Defines a flex container

flex-direction Row or column layout

justify-content Horizontal alignment

align-items Vertical alignment

flex-wrap Wraps items

Example
.container {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
}

9. Grid Properties
CSS Grid Layout allows you to design web pages using a two-dimensional grid.
Important Grid Properties

Property Description

display: grid Declares a grid container

grid-template-columns Defines columns

grid-template-rows Defines rows

gap Sets space between grid items

grid-area Specifies grid placement

Example
.grid {
display: grid;
grid-template-columns: 1fr 2fr;
gap: 10px;
}

10. Transition and Animation Properties


CSS enables animation effects and transitions for dynamic interactivity.
Transition Properties

Property Description

transition Short-hand for setting transitions

transition-duration Sets the time of transition

transition-timing-function Easing functions


Animation Properties

Property Description

animation-name Keyframe animation name

animation-duration Total time for animation

animation-iteration-count Number of repetitions

Example
button {
transition: background-color 0.5s ease-in-out;
}
button:hover {
background-color: lightgreen;
}

Controlling Text in CSS

Introduction
Text is one of the primary components of any website. Controlling its appearance is essential for
ensuring readability, accessibility, and visual appeal. CSS (Cascading Style Sheets) provides a wide
range of text properties that help designers and developers manipulate the presentation of textual
content within HTML documents.
By applying CSS, you can modify:
• Font styles and sizes
• Text alignment
• Spacing between characters and lines
• Text transformation (uppercase/lowercase)
• Decoration such as underlining or striking through
Proper control of text improves user experience and supports branding consistency.
1. Font Properties
Font properties are used to define how text appears in terms of typeface, style, and size.
a. font-family
Defines the typeface used for text. Multiple font options are listed for fallback purposes.
p{
font-family: 'Arial', 'Helvetica', sans-serif;
}
b. font-size
Specifies the size of the text. It can be set in px, em, rem, %, etc.
h1 {
font-size: 36px;
}
c. font-style
Used to apply italic styling.
em {
font-style: italic;
}
d. font-weight
Controls the thickness of the text.
strong {
font-weight: bold;
}
e. font-variant
Used for small caps style.
span {
font-variant: small-caps;
}
f. Shorthand Property
You can combine all font properties using font.
p{
font: italic bold 16px/1.5 'Georgia', serif;
}

2. Text Color and Decoration


These properties control the color and visual style of the text.
a. color
Sets the text color.
p{
color: darkblue;
}
b. text-decoration
Applies lines like underline, overline, line-through.
a{
text-decoration: none;
}
Values include:
• none
• underline
• line-through
• overline
c. text-shadow
Applies shadow to text for visual depth.
h2 {
text-shadow: 2px 2px 5px grey;
}

3. Text Alignment and Indentation


These properties control how text is positioned inside its container.
a. text-align
Aligns the text horizontally.
h1 {
text-align: center;
}
Common values:
• left
• right
• center
• justify
b. text-indent
Indents the first line of a paragraph.
p{
text-indent: 50px;
}

4. Text Spacing
Spacing properties allow you to adjust the space between characters and lines for better readability.
a. letter-spacing
Controls space between characters.
p{
letter-spacing: 2px;
}
b. word-spacing
Controls space between words.
p{
word-spacing: 10px;
}
c. line-height
Sets vertical spacing between lines.
p{
line-height: 1.8;
}

5. Text Transformation and Case


These properties are used to change the case of the text.
a. text-transform
Converts the text to uppercase, lowercase, or capitalized format.
h1 {
text-transform: uppercase;
}
Values:
• uppercase
• lowercase
• capitalize
• none

6. Direction and Writing Mode


Used for setting text direction for multilingual websites.
a. direction
Defines the direction of the text (left-to-right or right-to-left).
div {
direction: rtl;
}
b. unicode-bidi
Used with direction for bidirectional text.
c. writing-mode
Sets vertical or horizontal text direction.
p{
writing-mode: vertical-rl;
}

7. White Space and Overflow Handling


These properties help preserve or control whitespace and how text behaves inside boxes.
a. white-space
Controls how whitespace and line breaks are handled.
pre {
white-space: pre;
}
Values:
• normal
• nowrap
• pre
• pre-wrap
• pre-line
b. overflow-wrap
Breaks long words to avoid overflow.
p{
overflow-wrap: break-word;
}

8. CSS Pseudo-elements for Text


Pseudo-elements help apply styles to parts of the text content.
Examples
p::first-letter {
font-size: 200%;
color: red;
}

p::first-line {
font-weight: bold;
}
They are useful in:
• Drop caps
• Highlighting the first line
• Custom quotes (::before and ::after)

9. Responsive Typography
In modern web design, controlling text responsively is crucial.
Relative Units
• em – relative to parent font size
• rem – relative to root font size
• % – percentage of parent
Media Queries for Text
@media screen and (max-width: 600px) {
body {
font-size: 14px;
}
}

10. Example: Complete Text Styling Block


body {
font-family: 'Verdana', sans-serif;
font-size: 16px;
color: #333;
line-height: 1.6;
text-align: justify;
letter-spacing: 0.5px;
text-decoration: none;
}

Text Formatting in CSS

Introduction
Text formatting is one of the most essential aspects of web design and development. With CSS
(Cascading Style Sheets), you can apply advanced formatting to text elements in HTML to improve
visual appeal, readability, and user engagement. CSS text formatting controls everything from font
style and weight to alignment, decoration, transformation, spacing, and more.
Understanding how to format text using CSS ensures that websites are both aesthetically pleasing
and functionally responsive across various devices and screen sizes.

1. Font Styling
CSS offers several properties to format the appearance of fonts.
a. font-family
Specifies the typeface used. Always include fallback fonts.
p{
font-family: "Arial", "Helvetica", sans-serif;
}
b. font-size
Determines the size of the text. Units can be px, em, rem, %, etc.
p{
font-size: 18px;
}
c. font-style
Used to italicize text.
em {
font-style: italic;
}
d. font-weight
Specifies the boldness of text.
strong {
font-weight: bold;
}
e. font-variant
Displays text in small capital letters.
p{
font-variant: small-caps;
}
f. Shorthand property
p{
font: italic bold 16px/1.5 "Times New Roman", serif;
}

2. Text Alignment and Indentation


Alignment is crucial for the layout and presentation of content.
a. text-align
Controls the horizontal alignment of text.
h1 {
text-align: center;
}
Values:
• left
• right
• center
• justify
b. text-indent
Adds indentation to the first line of a paragraph.
p{
text-indent: 50px;
}

3. Text Decoration
Text decoration is used for visual effects like underlining, overlining, and strikethrough.
a. text-decoration
a{
text-decoration: none;
}
Values:
• none
• underline
• overline
• line-through
b. text-shadow
Applies shadow to text.
h2 {
text-shadow: 2px 2px 5px grey;
}
4. Text Transformation
Text transformation allows developers to alter the case of text.
a. text-transform
h1 {
text-transform: uppercase;
}
Values:
• uppercase
• lowercase
• capitalize
• none

5. Spacing and Height


These properties control the distance between text elements.
a. letter-spacing
Adjusts the space between characters.
p{
letter-spacing: 1px;
}
b. word-spacing
Controls spacing between words.
p{
word-spacing: 5px;
}
c. line-height
Adjusts spacing between lines.
p{
line-height: 1.6;
}
These settings improve legibility, especially in long-form content.

6. White-Space Control
White space formatting ensures how spaces and line breaks behave.
a. white-space
pre {
white-space: pre;
}
Values:
• normal (default)
• nowrap
• pre
• pre-wrap
• pre-line
b. overflow-wrap
Controls how long words are broken into new lines.
div {
overflow-wrap: break-word;
}

7. Pseudo-Elements for Text Formatting


Pseudo-elements enable you to style specific parts of the text.
a. ::first-letter and ::first-line
p::first-letter {
font-size: 200%;
color: red;
}

p::first-line {
font-weight: bold;
}
b. ::before and ::after
Used to insert content before/after an element.
blockquote::before {
content: "“";
font-size: 2em;
}

8. Writing Direction and Orientation


Used in multilingual or vertically formatted websites.
a. direction
div {
direction: rtl;
}
Values:
• ltr (left to right)
• rtl (right to left)
b. writing-mode
p{
writing-mode: vertical-rl;
}

9. Real-Time Example: Complete Formatting


body {
font-family: 'Georgia', serif;
font-size: 18px;
line-height: 1.8;
color: #222;
text-align: justify;
letter-spacing: 0.5px;
word-spacing: 1px;
text-transform: capitalize;
text-decoration: none;
text-shadow: 1px 1px 2px #999;
}
This example applies multiple formatting rules to create elegant and readable content.
10. Responsive Text Formatting
a. Using Relative Units
Use em, rem, or % instead of fixed px.
h1 {
font-size: 2rem;
}
b. Media Queries
@media (max-width: 768px) {
body {
font-size: 14px;
}
}
Responsive text formatting ensures accessibility and usability on mobile, tablets, and desktops.

Text Pseudo-Classes in CSS

Introduction
Pseudo-classes in CSS are special keywords that allow you to target elements based on their state or
position within the document. When it comes to text, pseudo-classes can be used to enhance the way
text behaves on different user interactions, such as hovering over a link or focusing on an input field.
These pseudo-classes provide a dynamic way to style text elements based on user interaction,
document structure, or specific states. By using them effectively, web developers can create more
interactive and visually appealing websites.

1. What are Pseudo-Classes?


A pseudo-class is used to define the special state of an element. It can target an element based on its
state in the DOM (Document Object Model) or its position in the document.
CSS pseudo-classes are prefixed with a colon (:), followed by the state or condition. Some of the most
common pseudo-classes are :hover, :focus, and :nth-child.

2. Common Text Pseudo-Classes


CSS offers a variety of pseudo-classes specifically for text elements. These pseudo-classes can be
used to style the text differently depending on its state, such as when a user interacts with it or when it
is in a particular structural position.
a. :link
The :link pseudo-class targets unvisited links. It is used to apply styles to links that the user has not
yet clicked on.
a:link {
color: blue;
text-decoration: none;
}
b. :visited
The :visited pseudo-class is used to target links that the user has already visited. It helps distinguish
between clicked and unclicked links.
a:visited {
color: purple;
}
c. :hover
The :hover pseudo-class targets elements when the user hovers over them with the mouse pointer. For
text, this is often used to create interactive effects on links or buttons.
a:hover {
color: red;
text-decoration: underline;
}
d. :focus
The :focus pseudo-class is applied to an element when it gains focus, typically when a user clicks on
an input field or navigates to it using the keyboard (Tab key).
input:focus {
background-color: yellow;
}
This pseudo-class is crucial for improving accessibility and enhancing the user experience when
interacting with form fields.
e. :active
The :active pseudo-class targets an element when it is being activated, such as when a user clicks on a
link or button.
a:active {
color: green;
}
It’s often used for buttons and links, providing feedback to the user that the element is being clicked.
3. Structural Text Pseudo-Classes
These pseudo-classes target text based on its position or order within the document, which can help
style lists, paragraphs, or other elements differently depending on their location.
a. :first-child
The :first-child pseudo-class selects an element that is the first child of its parent.
p:first-child {
font-weight: bold;
}
This is often useful when you want to style the first element in a group of similar elements, like the
first paragraph in a set of paragraphs.
b. :last-child
The :last-child pseudo-class targets the last child element of a parent.
p:last-child {
margin-bottom: 0;
}
This can be used to modify the appearance or layout of the last item in a list or group.
c. :nth-child()
The :nth-child() pseudo-class allows you to target elements based on their position in a parent
container. It can accept a number, keyword, or formula to select specific children.
li:nth-child(odd) {
color: blue;
}
This targets every odd child in a list. You can use even for even-numbered children or a formula to
define a custom pattern.
p:nth-child(3n) {
font-style: italic;
}
d. :nth-of-type()
The :nth-of-type() pseudo-class is similar to :nth-child(), but it selects elements based on their type,
rather than just their order in the parent.
p:nth-of-type(2) {
font-size: 18px;
}
This will style the second <p> tag in a container, ignoring other types of elements within the same
parent.

4. Dynamic Text Effects with Pseudo-Classes


CSS pseudo-classes can be particularly useful for creating dynamic visual effects. They enable you
to respond to user actions and state changes dynamically without JavaScript.
a. Interactive Links
Combining :link, :visited, :hover, and :active allows you to create rich, interactive link designs.
a:link {
color: blue;
}

a:visited {
color: purple;
}

a:hover {
color: red;
text-decoration: underline;
}

a:active {
color: green;
}
b. Focus States
For accessibility, it’s important to style elements that are focused, especially form elements. This
ensures that keyboard users can easily identify which element is active.
input:focus, textarea:focus {
border-color: blue;
outline: none;
}
c. Highlighting Special Text
You can highlight specific text based on its position, such as using :first-child to make the first
paragraph stand out or :nth-of-type for more complex styling.
p:first-child {
font-weight: bold;
}

p:nth-of-type(3) {
color: red;
}

5. Combining Pseudo-Classes for Complex Selectors


Pseudo-classes can be combined to target specific states or positions more precisely. By chaining
multiple pseudo-classes, you can apply styles under more complex conditions.
p:first-child:hover {
color: blue;
}

a:focus:active {
color: green;
}
These selectors allow for fine-grained control over text styling, responding to multiple conditions at
once.

6. Example: Combining Pseudo-Classes with Responsive Design


To enhance interactivity and readability, you can use pseudo-classes in conjunction with media
queries to adapt the layout and text formatting for different devices.
@media (max-width: 768px) {
a:link {
font-size: 16px;
}

a:hover {
color: orange;
}
}
This rule ensures that text formatting, like font size and color, adjusts when viewed on smaller
screens, enhancing user experience.

CSS Selectors

CSS (Cascading Style Sheets) selectors are the part of CSS rules used to target HTML elements and
apply styles to them. Selectors are essential in defining how styles apply to elements across a
webpage. Understanding the different types of selectors enables web developers to write more
organized, efficient, and specific CSS code.
This answer explains the following key selectors:
• Universal Selector
• Type Selector
• Class Selector
• ID Selector
• Grouping Selector
• Child Selector
• Descendant Selector
• Sibling Selector
• Adjacent Selector
• Attribute Selector
• Pseudo-Class Selector

1. Universal Selector (*)


The Universal Selector targets all HTML elements in a webpage. It is a general selector and is often
used to apply a common base style or reset default styles.
Syntax:
*{
margin: 0;
padding: 0;
}
Explanation:
• This code sets the margin and padding of every element to zero.
• Helpful for CSS resets or global styling.
Use Case:
Apply a base font or color scheme:
*{
font-family: Arial, sans-serif;
color: #333;
}

2. Type Selector (Element Selector)


Type selectors target elements based on their tag name such as <p>, <h1>, <div>, etc.
Syntax:
h1 {
color: blue;
}
Explanation:
• This code sets the text color of all <h1> tags to blue.
• It is one of the most commonly used selectors.
Use Case:
p{
line-height: 1.5;
}
Applies a line height of 1.5 to all paragraph elements.

3. Class Selector (.)


Class selectors allow you to apply styles to multiple elements by targeting a shared class name.
Syntax:
.box {
border: 1px solid black;
}
HTML:
<div class="box">Box 1</div>
<p class="box">Box 2</p>
Explanation:
• Targets any element with the class="box" attribute.
• Multiple elements can share the same class for reusable styles.

4. ID Selector (#)
ID selectors are used to style a single unique element. IDs must be unique within the HTML
document.
Syntax:
#header {
background-color: gray;
}
HTML:
<div id="header">This is the header</div>
Explanation:
• Targets only the element with id="header".
• Typically used for layout sections like navigation, footer, etc.

5. Grouping Selector
Grouping selectors allow you to apply the same style to multiple elements using a single rule,
separated by commas.
Syntax:
h1, h2, h3 {
font-family: Georgia, serif;
}
Explanation:
• Applies the same font to all three heading types.
• Reduces redundancy in code.
Use Case:
a, button, input[type="submit"] {
cursor: pointer;
}

6. Child Selector (>)


The Child Selector selects elements that are direct children of a specified parent element.
Syntax:
div > p {
color: green;
}
HTML:
<div>
<p>Direct child</p>
<section>
<p>Not a direct child</p>
</section>
</div>
Explanation:
• Only the <p> directly inside <div> is styled.
• Great for precise targeting of hierarchical elements.

7. Descendant Selector (space)


Descendant selectors target all elements nested within a specified element, regardless of nesting
level.
Syntax:
div p {
color: red;
}
Explanation:
• Styles all <p> elements inside <div>, even if deeply nested.
Use Case:
nav ul li {
list-style-type: none;
}
Removes bullets from all list items inside navigation menus.

8. Sibling Selector (~)


The General Sibling Selector selects all elements that are siblings and come after a specific element.
Syntax:
h2 ~ p {
color: blue;
}
HTML:
<h2>Heading</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
Explanation:
• Both paragraphs following the <h2> will be styled blue.
• Elements must be on the same nesting level.

9. Adjacent Sibling Selector (+)


The Adjacent Sibling Selector selects the first element immediately following a specified element.
Syntax:
h2 + p {
font-style: italic;
}
Explanation:
• Only the first <p> after <h2> is styled italic.
• Useful for targeting structured content like articles or forms.
Use Case:
label + input {
margin-left: 10px;
}

10. Attribute Selector


Attribute selectors allow you to style elements based on HTML attributes or values.
Syntax:
input[type="text"] {
border: 1px solid #ccc;
}
Types of Attribute Selectors:
• [attr]: Any element with the attribute.
• [attr="value"]: Specific value.
• [attr^="value"]: Starts with value.
• [attr$="value"]: Ends with value.
• [attr*="value"]: Contains value.
Use Case:
a[href^="https"] {
color: green;
}
Styles secure links (starting with https) differently.

11. Pseudo-Class Selectors


Pseudo-classes define special states of elements like hover, visited, nth-child, etc.
a. :hover
button:hover {
background-color: lightblue;
}
b. :first-child
ul li:first-child {
font-weight: bold;
}
c. :nth-child(n)
li:nth-child(odd) {
background-color: #f2f2f2;
}
d. :focus
input:focus {
outline: none;
border: 2px solid blue;
}

Lengths in CSS – Full Explanation


In CSS, lengths are used to define the size of elements, such as widths, heights, font sizes, margins,
paddings, and more. CSS supports a wide range of length units, both absolute and relative. Choosing
the right unit ensures a responsive, accessible, and visually consistent design.

1. Introduction to Lengths in CSS

Lengths in CSS are used to define how large or small elements appear. They are most commonly
applied to properties like:
• width
• height
• font-size
• margin, padding
• border-width
• line-height
• letter-spacing
• top, left, right, bottom (positioning)
Example:
div {
width: 200px;
padding: 10px;
font-size: 16pt;
}
CSS lengths are categorized into:
• Absolute units
• Relative units

2. Absolute Length Units


Absolute length units are fixed and do not scale with the screen size or user settings. They are best
used for print layouts or when the design must not be responsive.
Common Absolute Units:

Unit Description Example


px Pixels (most common) font-size: 16px;

pt Points (1pt = 1/72 inch) font-size: 12pt;


cm Centimeters width: 10cm;

mm Millimeters height: 20mm;

in Inches (1in = 2.54cm = 96px) width: 2in;

pc Picas (1pc = 12pt) font-size: 2pc;

Example:
p{
font-size: 14pt;
line-height: 1.5in;
}

Note: px is the most used absolute unit in screen-based web development.

3. Relative Length Units


Relative units are scalable and responsive to screen size, user preferences, or parent element sizes.
These are best suited for modern web design.
Common Relative Units:
Unit Description Example

em Relative to the font-size of the parent padding: 2em;

rem Relative to the root font-size font-size: 1.2rem;

% Percentage of parent element width: 80%;

vw Viewport width (1vw = 1% of viewport width) font-size: 5vw;

vh Viewport height height: 50vh;

vmin Smaller of vw or vh width: 10vmin;

vmax Larger of vw or vh width: 10vmax;

ch Width of the "0" character width: 60ch;

ex Height of the "x" character (rare) font-size: 2ex;

Example:
html {
font-size: 16px;
}

h1 {
font-size: 2rem; /* = 32px */
}

p{
font-size: 1.5em; /* relative to parent */
}

4. em vs rem

Unit Depends On Use Case

em Font size of the parent element Nested styling, modular design

rem Font size of the root element (html) Global responsiveness

Example:
html {
font-size: 16px;
}

section {
font-size: 20px;
}

section p {
font-size: 1em; /* 20px */
}

section p span {
font-size: 2em; /* 40px, relative to p */
}
Using rem provides predictability, while em allows local scaling.

5. Viewport Units (vw, vh, vmin, vmax)


These units allow sizing relative to the browser window (viewport).

Unit Description

vw 1% of the viewport's width


vh 1% of the viewport's height

vmin Smaller of vw or vh

vmax Larger of vw or vh

Example:
div {
width: 80vw;
height: 60vh;
}
Useful for creating full-screen layouts, responsive headings, and flexible content boxes.

6. Percentage (%) Lengths


Percentages are always relative to a parent element.
Example:
.container {
width: 100%;
}

.box {
width: 50%;
}
If .container is 800px wide, then .box becomes 400px.
Important: Percentages behave differently depending on the property:
• width, height: Relative to parent box
• padding, margin: Relative to parent’s width
• font-size: Not percentage based

7. Combining Length Units


Modern web design often combines multiple units for responsive, accessible, and scalable UIs.
Example:
:root {
font-size: 16px;
}
body {
font-size: 1rem; /* 16px */
padding: 2vw 1em;
}

h1 {
font-size: 4vw;
}
This mix ensures consistent design across desktop, tablet, and mobile screens.

8. Best Practices in Using Lengths


• Use rem for consistent font sizing across the project.
• Use % or vw for fluid layouts.
• Avoid using too many absolute units (px, pt) for responsive designs.
• Use a CSS reset or base font size for consistency.
• Test how lengths behave across different screen sizes.

9. Practical Examples
Responsive Box:
.container {
width: 90%;
padding: 2em;
font-size: 1.2rem;
}
Fullscreen Section:
.fullscreen {
height: 100vh;
width: 100vw;
}
Typography:
h2 {
font-size: 2.5rem;
}

p{
font-size: 1em;
line-height: 1.5em;
}

Introducing the Box Model in CSS

CSS (Cascading Style Sheets) uses a box model concept to wrap every HTML element in a
rectangular box. This model describes how the element occupies space on a webpage and helps
developers control layout, spacing, borders, and positioning.
Understanding the CSS Box Model is essential for building well-structured, responsive, and visually
appealing websites.

1. What is the CSS Box Model?


The CSS Box Model is a foundational concept in CSS that determines how elements are displayed
and how their spacing and size are calculated.
Each HTML element is treated as a box with the following components:
1. Content – The actual content such as text or image.
2. Padding – Space around the content, inside the border.
3. Border – The line that wraps the content and padding.
4. Margin – Space outside the border, separating the element from others.
Diagram (Text Representation):
2. Parts of the Box Model Explained
a. Content
• The actual text, image, or other media.
• Width and height are first calculated based on the content area.
div {
width: 200px;
height: 100px;
}
b. Padding
• Clears an area around the content.
• Inside the element’s border.
• Transparent by default.
div {
padding: 20px;
}
c. Border
• A line surrounding the padding and content.
• Can be styled using width, style, and color.
div {
border: 2px solid black;
}
d. Margin
• Clears an area outside the border.
• Used to create space between elements.
div {
margin: 15px;
}

3. Total Width and Height Calculation


The total size of an element depends on the content, padding, border, and margin.
Formula:
Total Width = content width + left/right padding + left/right border + left/right margin
Total Height = content height + top/bottom padding + top/bottom border + top/bottom margin
Example:
div {
width: 200px;
padding: 10px;
border: 5px solid black;
margin: 15px;
}
Total width = 200 + 10+10 + 5+5 + 15+15 = 260px
Total height = same logic applies

4. Box-Sizing Property
The box-sizing property changes how width and height are calculated.
Values:

Value Description

content-box Default. Width includes only content. Padding and border are added.

border-box Width includes content + padding + border. More intuitive layout.

Example:
div {
width: 300px;
padding: 20px;
border: 10px solid black;
box-sizing: border-box;
}
Here, the total width remains 300px, unlike in the default content-box.

5. Practical Example
HTML:
<div class="box">Hello World</div>
CSS:
.box {
width: 200px;
padding: 20px;
border: 2px solid red;
margin: 10px;
}
Result:
• Content width = 200px
• Padding = 40px total (20 left + 20 right)
• Border = 4px total
• Margin = 20px total
• Total width = 264px
Without setting box-sizing: border-box, the element visually expands beyond the set width.

6. Collapsing Margins
Margin collapsing occurs when two vertical margins meet. Instead of adding, the browser uses only
the larger one.
Example:
div1 {
margin-bottom: 20px;
}

div2 {
margin-top: 30px;
}
The total space between them is 30px, not 50px.

7. Box Model Use in Layouts


Using the box model, we can build flexible layouts:
• Control spacing between elements.
• Define borders for visual separation.
• Apply padding to keep text from touching borders.
• Use margin to center blocks (margin: auto).
• Prevent layout overflow using box-sizing: border-box.

8. Developer Tools and Box Model


Modern browsers like Chrome and Firefox provide Developer Tools that visually show the box
model.
• Right-click on an element → Inspect.
• Box model is displayed with:
o Content
o Padding
o Border
o Margin
This helps in debugging layout and spacing issues.

9. Best Practices
• Use box-sizing: border-box; globally to simplify width/height calculation:
*{
box-sizing: border-box;
}
• Always define padding and margin thoughtfully for mobile responsiveness.
• Use consistent units (px, rem, %) to maintain uniformity.

You might also like