Module 2-1
Module 2-1
Module 2
CSS3 and Responsive Web Design: CSS3 Basics:
SS3isthelatestevolutionoftheCascadingStyleSheetslanguageandaimsatextendingCSS2.1.Itbringsa
C
lot of long-awaited novelties, like roundedcorners,shadows,gradients,transitionsoranimations,aswellas
new layouts like multi-columns, flexible box or grid layouts.
CSS Selectors
hinkofaselectorasawayofpointingatspecificelementsintheHTMLdocument.Forexample,youmight
T
want to change the text color of all paragraphs or set the background of an element with a certain class.
c ss
selector {
property: value;
}
● Property: Defines what style aspect to change (e.g., color, font-size).
Example:
c ss
p {
color: blue;
}
SSprovidesmanytypesofselectorstotargetelementswithvariouslevelsofprecision.Belowarethemain
C
types:
● Useful for applying global styles like margin or padding resets.
Example:
css
* {
margin: 0;
padding: 0;
}
This removes all default margins and paddings from every element, giving a clean slate.
Example:
css
h1 {
font-size: 36px;
color: darkblue;
}
This styles all <h1> elements with a larger font and dark blue color.
Syntax:
c ss
.className {
/* styles */
}
Example:
c ss
.highlight {
background-color: yellow;
font-weight: bold;
}
HTML:
html
Syntax:
css
#elementID {
/* styles */
}
Example:
c ss
#main-header {
text-align: center;
f ont-size: 48px;
}
HTML:
h tml
<h1 id="main-header">Welcome to My Website</h1>
Syntax:
Example:
c ss
input[type="text"] {
border: 2px solid green;
padding: 5px;
}
Common pseudo-classes:
Example:
c ss
a:hover {
color: red;
text-decoration: underline;
}
When the user hovers over a link, it becomes red and underlined.
● They let you insert or style parts like the first letter, before or after content, selection, etc.
Common pseudo-elements:
Example:
c ss
p::first-letter {
font-size: 200%;
color: orange;
}
This makes the first letter of every paragraph larger and orange.
These selectors target elements based on their relationship in the HTML structure.
a ) D
escendant Selector (space)
● Selects elements that are inside another element, no matter how deep.
css
div p {
color: green;
}
b ) C
hild Selector (>)
● Selects direct children only (one level down).
c ss
ul > li {
list-style-type: circle;
}
c ) A
djacent Sibling Selector (+)
● Selects the element immediately after another element.
c ss
h2 + p {
margin-top: 0;
}
d ) G
eneral Sibling Selector (~)
● Selects all siblings after a specific element.
css
h3 ~ p {
color: gray;
}
hen multiple CSS rules apply to the same element, the browser decides which to use by calculating
W
specificity.
Specificity rules:
Example:
css
p {
color: blue; /* specificity = 1 */
}
.highlight {
color: red; /* specificity = 10 */
}
#intro {
color: green; /* specificity = 100 */
}
If a paragraph has class highlight and id intro, the text will be green because ID selector specificity is highest.
You can group selectors that share the same styles using commas, reducing repetition.
Example:
css
h1, h2, h3 {
font-family: Arial, sans-serif;
color: navy;
}
● CSS selectors let you target HTML elements for styling.
● T here are many types: universal, type, class, ID, attribute, pseudo-class, pseudo-element, and
combinators.
SS3 properties are the style attributes that determine how HTML elements appear on a webpage. They
C
describe what aspect of the element to style, such as color, size, spacing, font, and layout.
● color
● margin
● padding
● font-size
● background
● border
CSS3 Values
aluesarethespecificsettingsassignedtoCSSproperties.Theydefinehowthepropertyshouldbeappliedto
V
the element.
For example:
c ss
p {
color: blue;
margin: 10px;
}
Here, color and margin are properties, and blue and 10px are their respective values.
○ margin-top
○ margin-right
○ margin-bottom
○ margin-left
hese allow multiple related longhand properties to be set together in one declaration.
T
For example, margin can set all four margins at once:
c ss
margin: 10px 20px 15px 5px;
This means:
padding-left: 15px;
/* longhand padding on left */
background-color: #f0f0f0;
/* hexadecimal color value */
width: 75%;
/* percentage width relative to parent */
font-size: 1.2em;
/* relative font size */
display: flex;
/* keyword value */
}
Summary
● CSS3 values assign the specific style settings to those properties.
● Values vary in type, including lengths, colors, keywords, percentages, URLs, and functions.
● Understanding both properties and values is essential to write effective and flexible CSS code.
Box model
he CSS3 Box Model is a fundamental concept in CSS that describes how elements on a webpage are
T
structured and how their sizes and spacing are calculated. Every HTML element is represented as a
rectangular box, and this box consists of several layers that define the element’s total space on the page.
Understanding the box model is crucial for designing and controlling layouts effectively.
The CSS box model has four main parts from inside out:
○ The innermost part containing the actual content, such as text, images, or other media.
○ The size of the content box is set by the CSS properties width and height.
2. Padding
○ The transparent space surrounding the content inside the element.
○ Padding pushes the content away from the element’s edges.
○ It increases the size of the element’s box but stays inside the border.
3. Border
○ Borders can have width, style (solid, dotted, dashed), and color.
4. Margin
○ Margin creates distance between the element and other neighboring elements.
○ M arginsdonothaveabackgroundanddonotaffecttheelement’svisiblesize,onlythespace
around it.
The total size of an element depends on the sum of its content, padding, border, and margin.
● T otalWidth=contentwidth+leftpadding+rightpadding+leftborder+rightborder+leftmargin+
right margin
● T otal Height = content height + top padding + bottom padding + top border +bottomborder+top
margin + bottom margin
Example:
css
div {
width: 200px;
padding: 10px;
ydefault,CSSusesthecontent-boxmodel,whichmeansthewidthandheightapplyonlytothecontentarea.
B
Padding and borders are added outside this size, increasing the total size of the element.
● c ontent-box(default):Widthandheightincludeonlythecontent.Paddingandborderincreasethetotal
size.
● b order-box:Widthandheightincludecontent+padding+border.Thetotalsizeremainsthevalueset
in CSS, making layout calculations easier.
Example:
css
div {
width: 300px;
padding: 20px;
border: 5px solid black;
box-sizing: border-box;
}
Here, the total width of the element will be 300px, with padding and border included inside the 300px width.
● Layout Control: Helps in managing the spacing and size of elements on the page precisely.
● Styling Accuracy: Avoids common bugs caused by padding and borders adding extra space.
● B rowserConsistency:CSS3box-sizingissupportedwidely,allowingconsistentstylingacrossmodern
browsers.
Summary
● The CSS3 box model treats each element as a box with content, padding, border, and margin.
● The total size of an element includes all these parts unless box-sizing: border-box is used.
● T hebox-sizingpropertysimplifieslayoutbyincludingpaddingandborderwithintheelement’swidth
and height.
● Mastering the box model is key to professional and precise web design.
SS3providesmultiplewaystocontroltheflowandpositionofelements,includingtraditionalmethodsand
C
modern techniques like Flexbox and Grid.
The position property specifies how an element is positioned in a document. It accepts several values:
2. Relative
○ You can move it using top, right, bottom, and left without affecting other elements' positions.
○ Space is still reserved for the element in the normal flow.
3. Absolute
○ Element is positioned relative to the nearest positioned ancestor (relative, absolute, or fixed).
○ Removed from normal document flow; does not affect other elements.
○ You control its exact position using top, right, bottom, and left.
4. Fixed
○ Element is positioned relative to the viewport and stays fixed when the page is scrolled.
○ Removed from normal flow; top, right, bottom, and left specify its position.
○ Element behaves like relative until it reaches a defined scroll position, then it becomes fixed.
● The default layout where block elements stack vertically and inline elements flow horizontally.
● f loat:Allowselementstobetakenoutofnormalflowandfloatedleftorright,enablingtextorinline
elements to wrap around them.
Float was widely used for layouts before modern techniques but can be tricky and requires clearing floats.
● Key properties: display: flex;, justify-content, align-items, flex-wrap, flex-grow, order, etc.
Example:
c ss
.container {
display: flex;
justify-content: space-between;
align-items: center;
}
Flexbox adapts well to different screen sizes and is great for menus, toolbars, and small layouts.
● Key properties: display: grid;, grid-template-columns, grid-template-rows, grid-gap, grid-area, etc.
Example:
c ss
.container {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
grid-gap: 10px;
}
Grid is powerful for complex layouts like entire webpages and dashboard designs.
● top, right, bottom, left — Define offsets for positioned elements.
lexboxisaCSS3layoutmoduledesignedforone-dimensionallayouts,meaningitarrangesitemsinarowor
F
acolumn.Ithelpsalignanddistributespaceamongitemsinacontainer,evenwhentheirsizesareunknownor
dynamic.
Key Concepts
● The flex container is the parent element with display: flex; or display: inline-flex;.
● The flex items are the direct children of the flex container.
Property Description
flex-direction Sets the direction of flex items (row, column, row-reverse, column-reverse).
justify-content ligns items horizontally (main axis). Values: flex-start, center, flex-end,
A
space-between, space-around.
align-items ligns items vertically (cross axis). Values: stretch (default), flex-start,
A
center, flex-end, baseline.
align-content lignsmultiplerowswhenwrappingoccurs(likejustify-contentbutforcross
A
axis).
Property Description
flex-grow Defines how much a flex item will grow relative to others.
flex-shrink Defines how much a flex item will shrink relative to others.
flex-basis Sets the initial size of a flex item before growing or shrinking.
Example
c ss
.container {
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: center;
flex-wrap: wrap;
}
.item {
flex-grow: 1;
flex-basis: 150px;
}
SSGridisatwo-dimensionallayoutsystemforbothrowsandcolumns.Itallowsprecisecontroloverlayout
C
by defining grid tracks (rows and columns) and placing items explicitly.
Key Concepts
● The grid items are the direct children of the grid container.
● The grid consists of rows and columns forming grid cells.
Property Description
grid-template-columns Defines the columns and their widths (e.g., 100px 1fr 2fr).
grid-gap / gap Defines the spacing (gutter) between rows and columns.
grid-auto-flow Controls how auto-placed items are inserted (row, column, dense).
Property Description
grid-column-start The line where the item starts on the column axis.
grid-column-end The line where the item ends on the column axis.
grid-row-start The line where the item starts on the row axis.
grid-row-end The line where the item ends on the row axis.
Example
css
.container {
display: grid;
grid-template-columns: 150px 1fr 1fr;
grid-template-rows: 100px auto;
grid-gap: 10px;
}
.item1 {
grid-column: 1 / 2;
grid-row: 1 / 3;
}
.item2 {
grid-column: 2 / 4;
grid-row: 1 / 2;
}
Types of responsive
media is a method or rule to apply conditions on different-different screen sizesandstartcontrollingthe
@
design and the layout of full website
Important Properties
ax-width : 600px
m
min-width : 600px
ith the proliferation of devices ranging from small smartphones to large desktop monitors, it became
W
essential for websites to adapt their layout and content fluidly to provide a consistent and user-friendly
experience.ResponsiveWebDesignistheapproachthatmakesthispossiblebyallowingwebpagestodetect
theuser’sscreensize,orientation,andresolution,andadjustthelayoutaccordinglywithoutneedingseparate
mobile or desktop versions.
edia QueriesarethebackboneofResponsiveWebDesign.TheyallowthebrowsertoapplydifferentCSS
M
styles depending on the device or viewport characteristics.
● M ediaqueriesenabledesignerstospecifystylerulesthatactivateonlyifcertainconditionsaboutthe
device are met, such as screen width, height, or orientation.
● This means the same HTML content can look completely different on a smartphone, tablet, or desktop.
● M ediaqueriesareessentialfortailoringuserinterfacestodiversedeviceswithoutduplicatingcodeor
maintaining multiple versions of a site.
● T hey support a wide range of device features, not just screen size — including resolution (pixel
density), aspect ratio, and even user preferences like color schemes (dark or light mode).
● A common use of media queries is to define breakpoints — specific widths at which the layout
changes dramatically to better suit the screen size.
● B reakpoints often correspond to common device widths (e.g., 320px for phones, 768px for tablets,
1024px+ for desktops).
● T hepowerofmediaqueriesliesintheirabilitytoadaptthesamecontentfluidlyinsteadofrelyingon
fixed layouts.
esponsive Design is guided by several key principles aimed at achieving flexibility and usability across
R
devices:
● Fluid grids replace fixed widths with relative measurements like percentages.
● This allows columns and containers to expand and contract proportionally to the viewport width.
● F or example, instead of saying a sidebar is 300 pixels wide, you might say it occupies 25% of the
container’s width.
● Fluid grids help maintain the spatial relationships between page elements regardless of screen size.
● T hisproportionalresizingresultsinabalancedandharmoniouslayoutwhetherviewedonaphoneora
widescreen monitor.
● D esigningwithfluidgridsrequirescarefulconsiderationofminimumandmaximumwidthstoprevent
elements from becoming too small or excessively stretched.
● F luid grids work hand-in-hand with media queries, where breakpoints adjust the number or
arrangement of grid columns based on screen size.
Flexible images are vital for preventing layout issues on varying screen sizes:
● I mages in traditional web design were often fixed in size, causing them to either overflow their
containers or be too small on larger screens.
● F lexible images use CSS properties that allow them to scale within the constraints of their parent
containers.
● Thegoalistomakesureimagesneverexceedthewidthoftheircontainerbutshrinkproportionallyto
maintain aspect ratio.
● This prevents horizontal scrolling caused by large images on small screens.
● I talsoimprovespageloadtimesonmobiledevicesbyenablingtechniquessuchasresponsiveimage
loading, where the browser selects an appropriately sized image based on screen size or resolution.
● F lexibleimagesmaintainvisualbalanceandensurecontentflowsnaturally,improvingaestheticsand
usability.
The mobile-first approach to responsive design reverses the traditional desktop-first mindset:
● T hisforcesthedesignertofocusoncorecontentandessentialfunctionality,ensuringthatmobileusers
have fast-loading, easy-to-navigate sites.
● A fterestablishingthemobilebaseline,stylesandfeaturesareprogressivelyaddedfortablets,laptops,
and desktops through media queries targeting larger screen widths.
● M obile-first design naturally aligns with performance optimization — mobile devices often have
slower connections and less processing power, so lightweight, efficient code is crucial.
● T his approach leads to simpler, more maintainable CSS, as the base styles serve mobile, with
enhancements layered on top for bigger devices.
● I t also aligns with search engine optimization (SEO) best practices, since mobile usability is a key
ranking factor.
CSS Frameworks
CSSFrameworkisapre-preparedlibrarythatprovidesafoundationofready-to-usestylesandcomponents
A
forbuildingwebsitesquicklyandconsistently.FrameworkshelpdevelopersavoidwritingrepetitiveCSScode
by offering:
sing a CSS framework speeds up development, ensures design consistency, and improves cross-browser
U
compatibility.
Bootstrap:
ootstrap is the most popular open-source CSS framework originally developed by Twitter. It provides a
B
comprehensive collection of tools to design responsive and mobile-first websites with ease.
Bootstrap Components
Bootstrap provides many pre-built UI components, including but not limited to:
● Buttons: Different styles, sizes, and states (primary, secondary, disabled, active).
● Forms: Styled input fields, selects, checkboxes, radio buttons, and validation feedback.
● Navigation Bars: Responsive navbars that collapse into a hamburger menu on small screens.
● Cards: Flexible content containers with headers, footers, images, and text.
● Alerts: Styled messages for success, warning, error, and info states.
These components help developers build complex interfaces without designing every element from scratch.
Bootstrap Utilities
Bootstrap’sutilityclassesallowquickcustomizationandlayoutadjustmentsbyaddingsmallclassesdirectly
in HTML, rather than writing CSS rules:
These utilities reduce CSS writing, increase development speed, and improve maintainability.
ootstrapisbuiltusingSass(SyntacticallyAwesomeStylesheets),apowerfulCSSpreprocessorthatextends
B
CSS with variables, nesting, functions, and more.
1. Bootstrap exposes a large number of variables for colors, font sizes, border-radius, and more.
2. You create a custom Sass file where you override these variables with your design preferences.
4. Finally, you compile the Sass into a CSS file that includes your customizations.
his method allows deep control over Bootstrap's appearance while still leveraging its powerful grid and
T
components.
Summary
Topic Description
Bootstrap Utilities Small helper classes for spacing, text, display, flexbox
Customizing with Sass Modify Bootstrap styles via Sass variables and partials