Module 2
2.3 CSS unit and size
CSS units help us control the size and spacing of elements on a webpage. Let's explore them interactively so you can see the results right away!
1️⃣ Absolute Units (Fixed Sizes)
Absolute units give a fixed size no matter what. Let’s see how they work!
px (pixels) Pixels are the most common absolute unit. They represent the smallest unit of display on your screen. Let’s see how it works!
🔹 Try it: Adjust the width and height of the box by changing px values.
2️⃣ Relative Units (Flexible Sizes)
Relative units adjust according to the parent element or viewport. Let's see how flexible they are!
% (percent) Percentage is relative to the parent element. If the parent changes, the child will adjust automatically.
🔹 Try it: Adjust the width of the box by changing the % value.
3️⃣ em and rem Units
The em and rem units are based on font sizes and are used for scalable designs.
em
The em unit is relative to the font size of the parent element.
🔹 Try it: Change the font size of the paragraph text, and watch how the em unit in the child element changes relative to it.
em (relative to the parent font size)
rem
The rem unit is relative to the root (html) font size.
🔹 Try it: Change the root font size in the <html> tag and see how rem behaves.
rem (relative to the root font size)
4️⃣ Viewport Units (Responsive Units)
Viewport units are super cool because they adjust to the screen size. Great for making your design responsive!
vw (viewport width)
The vw unit is based on 1% of the viewport’s width.
🔹 Try it: Change the width of the box to vw and watch how it scales based on the width of your browser window.
vw (viewport width)
vh (viewport height)
The vh unit is based on 1% of the viewport’s height.
🔹 Try it: Change the height of the box to vh and resize the window to see it respond!
vh (viewport height)
5️⃣ Interactive Challenge:
Mix Units for Responsiveness Let’s mix relative, absolute, and viewport units for a cool responsive layout.
🔹 Challenge Exercise:
Create a webpage with a responsive box that:
Has a width in %. Has a height in vh. Has a font size in em.
For a better understanding, watch the video below:👇
HTML+CSS Code for the Exercise:
👏 Great Job!