Block and Inline Elements
HTML has two main types of elements: block and inline. A correct understanding helps with layout and styling.
Block Elements
Block elements occupy the full available width and create a new line.
<div>Division</div>
<p>Paragraf</p>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<ul>
<li>Item</li>
</ul>
<table>
<tr><td>Cell</td></tr>
</table>
<form>
<input type="text">
</form>
Inline Elements
Inline elements only take up the width they need and don't create a new line.
<span>Text</span>
<a href="#">Link</a>
<strong>Bold</strong>
<em>Italic</em>
<img src="photo.jpg" alt="Image">
<input type="text">
<label>Label</label>
<button>Button</button>
Case Study: Dashboard Layout
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard Admin</title>
<style>
.container {
display: flex;
gap: 1rem;
}
.sidebar {
width: 200px;
background: #333;
color: white;
padding: 1rem;
}
.main {
flex: 1;
padding: 1rem;
}
.stat-box {
display: inline-block;
background: #f0f0f0;
padding: 1rem;
margin: 0.5rem;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="sidebar">
<h2>Menu</h2>
<ul>
<li>Dashboard</li>
<li>Student</li>
<li>Lecturer</li>
</ul>
</div>
<div class="main">
<h1>Dashboard</h1>
<div class="stat-box">
<h3>1,234</h3>
<p>Student</p>
</div>
<div class="stat-box">
<h3>56</h3>
<p>Lecturer</p>
</div>
<div class="stat-box">
<h3>12</h3>
<p>Major</p>
</div>
</div>
</div>
</body>
</html>
Everyday Case Study
Case: A developer needs to understand the difference between block and inline.
<!-- Block: occupies the full width -->
<div style="background: red; padding: 10px;">
Div 1
</div>
<div style="background: blue; padding: 10px;">
Div 2
</div>
<!-- Inline: only takes the width it needs -->
<span style="background: red; padding: 10px;">Span 1</span>
<span style="background: blue; padding: 10px;">Span 2</span>
Display Property
/* Block */
div { display: block; }
p { display: block; }
/* Inline */
span { display: inline; }
a { display: inline; }
/* Inline-block */
img { display: inline-block; }
button { display: inline-block; }
/* Flex */
.container { display: flex; }
/* Grid */
.grid { display: grid; }
Best Practices
- Block for structure: Use div, section, article
- Inline for content: Use span, a, strong
- CSS for layout: Use flexbox or grid
- Semantic elements: Use header, main, footer
- Accessibility: Consider screen readers
Summary
Block and inline elements behave differently. Understand the difference for correct layouts.