What is display block in CSS: Explanation and Examples
display: block makes an element behave like a block-level box, meaning it takes up the full width available and starts on a new line. Block elements stack vertically and can have width, height, margin, and padding applied easily.How It Works
Think of display: block like stacking boxes on a shelf. Each box (element) takes up the entire shelf width and sits below the previous box, never side-by-side. This means the element stretches across the container horizontally and pushes the next element down to a new line.
This behavior is different from inline elements, which sit side-by-side like words in a sentence. Block elements create clear sections on a page, making it easier to control layout and spacing.
Example
This example shows two elements with display: block. They each take full width and appear stacked vertically.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Display Block Example</title> <style> .block-box { display: block; width: 200px; height: 50px; background-color: #4CAF50; color: white; margin-bottom: 10px; text-align: center; line-height: 50px; font-family: Arial, sans-serif; } </style> </head> <body> <div class="block-box">Block Element 1</div> <div class="block-box">Block Element 2</div> </body> </html>
When to Use
Use display: block when you want elements to stack vertically and take up the full width or a set width. This is common for sections, paragraphs, div containers, and buttons that should appear on their own line.
For example, use block display for navigation menus, article sections, or form inputs to control layout clearly and predictably. It helps create clean, readable page structures.
Key Points
- Block elements start on a new line and take full width by default.
- You can set width, height, margin, and padding on block elements easily.
- Common block elements include
<div>,<p>, and<h1>to<h6>. display: blockcan be applied to inline elements to change their behavior.
Key Takeaways
display: block makes elements stack vertically and take full width by default.display: block.div, p, and headings.