Two very important concepts in CSS layout are:
If the Box Model controls spacing,
then Display and Positioning control layout and placement.
display PropertyThe display property decides how an element behaves in relation to other elements.
1️⃣ Block Elements (display: block)
Block elements:
Examples:
<div><p><h1>Example:
div {
display: block;
}
Even if you set a width smaller than the screen, block elements still start on a new line.
2️⃣ Inline Elements (display: inline)
Inline elements:
Examples:
<span><a><strong>Example:
span {
display: inline;
}
Inline elements sit next to each other.
3️⃣ Inline-Block (display: inline-block)
This is a combination of block and inline.
Inline-block elements:
Example:
.box {
display: inline-block;
width: 100px;
height: 100px;
}
Very useful for horizontal layouts.
4️⃣ None (display: none)
Removes the element completely from the page.
.hidden {
display: none;
}
The element disappears and takes up no space.
5️⃣ Flex (display: flex)
Used for modern layouts.
.container {
display: flex;
}
This makes child elements align in a row by default.
Example:
.container {
display: flex;
gap: 10px;
}
The position property controls where an element appears.
There are five main types:
1️⃣ Static (Default)
div {
position: static;
}
2️⃣ Relative
.box {
position: relative;
top: 20px;
left: 30px;
}
Think: "Move it slightly from where it normally sits."
3️⃣ Absolute
.box {
position: absolute;
top: 0;
right: 0;
}
Important:
If you want absolute inside a container:
.container {
position: relative;
}
Then the absolute child will stay inside that container.
4️⃣ Fixed
.box {
position: fixed;
bottom: 0;
right: 0;
}
Used for:
5️⃣ Sticky
.box {
position: sticky;
top: 0;
}
Used for:
Below is the full working example:
<!DOCTYPE html>
<html>
<head>
<title>Display and Positioning</title>
<style>
body {
font-family: Arial, sans-serif;
}
.inline-box {
display: inline-block;
width: 100px;
height: 100px;
background-color: lightblue;
margin: 5px;
text-align: center;
line-height: 100px;
}
.relative-box {
position: relative;
top: 20px;
left: 20px;
background-color: lightgreen;
padding: 10px;
margin-top: 20px;
}
.container {
position: relative;
height: 150px;
border: 2px solid black;
margin-top: 30px;
}
.absolute-box {
position: absolute;
top: 10px;
right: 10px;
background-color: pink;
padding: 10px;
}
.fixed-box {
position: fixed;
bottom: 10px;
right: 10px;
background-color: orange;
padding: 10px;
}
</style>
</head>
<body>
<h2>Display: Inline-Block</h2>
<div class="inline-box">Box 1</div>
<div class="inline-box">Box 2</div>
<div class="inline-box">Box 3</div>
<div class="relative-box">
This box is relatively positioned.
</div>
<div class="container">
Container
<div class="absolute-box">
Absolute Box
</div>
</div>
<div class="fixed-box">
Fixed Box
</div>
</body>
</html>