CSS Align
CSS Align
Aligning elements is a common task in CSS. Depending on what you want to align (text, block elements, inline elements), different techniques are used.
This section covers common ways to center and align elements horizontally and vertically.
Center Align
To center a block element horizontally, set a width and use margin: auto.
.box {
width: 420px;
margin: auto;
padding: 16px;
border: 1px solid #ddd;
border-radius: 12px;
}
To center text inside an element, use text-align: center.
.box {
text-align: center;
}
Horizontal Align
There are multiple ways to align items horizontally:
- Text and inline elements: use
text-alignon the parent - Block elements: use
margin-left/rightormargin: auto - Modern layouts: use Flexbox (
justify-content)
.row {
display: flex;
justify-content: center; /* left | center | right | space-between */
gap: 10px;
}
Vertical Align
Vertical alignment depends on the type of elements you are working with.
Inline elements: you can use vertical-align.
.icon {
vertical-align: middle;
}
Centering content vertically (recommended): use Flexbox.
.center-box {
height: 160px;
display: flex;
align-items: center; /* vertical */
justify-content: center; /* horizontal */
border: 1px solid #ddd;
border-radius: 12px;
}
Line-height trick (single line only): for one-line text, set line-height equal to height.
.single-line {
height: 48px;
line-height: 48px;
text-align: center;
}
Code Challenge
Goal: Center a badge inside a box both horizontally and vertically.
HTML:
<div class="panel"> <span class="badge">Centered</span> </div>
Task:
- Give the panel a fixed height
- Center the badge horizontally and vertically
- Add padding and a border for better appearance
Try a Solution:
.panel {
height: 160px;
padding: 16px;
border: 1px solid #ddd;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
}
.badge {
display: inline-block;
padding: 6px 12px;
border-radius: 999px;
border: 1px solid #d6e4ff;
background: #f3f6ff;
}
What’s Next?
Next, you will learn how combinators help you target elements based on their relationship in HTML.