How do I center a div?
- User
How do I center a div?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
How do I center a div?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Centering a <div> can be achieved using multiple CSS techniques. Below are the most common and reliable methods, categorized by use case:
For a <div> with a defined width:
.center-horizontal {
width: 50%; /* Define width */
margin: 0 auto; /* Top/Bottom = 0, Left/Right = auto */
}
<div class="center-horizontal">Content</div>
Use Flexbox on the parent container:
.parent {
display: flex;
justify-content: center; /* Horizontal */
align-items: center; /* Vertical */
height: 100vh; /* Full viewport height (optional) */
}
<div class="parent">
<div class="child">Centered Content</div>
</div>
Use Grid on the parent container:
.parent {
display: grid;
place-items: center; /* Centers both axes */
height: 100vh;
}
<div class="parent">
<div class="child">Centered Content</div>
</div>
Works for dynamic/unknown widths/heights:
.parent {
position: relative;
height: 100vh;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* Adjusts for element's own size */
}
<div class="parent">
<div class="child">Centered Content</div>
</div>
For elements like <span> or display: inline-block:
.parent {
text-align: center; /* Works for inline elements */
}
.child {
display: inline-block;
}
<div class="parent">
<div class="child">Centered Inline Content</div>
</div>
For a <div> centered in the entire window:
.center-viewport {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div class="center-viewport">Centered in Viewport</div>
All methods are widely supported in modern browsers. Let me know if you need help adapting this to your specific HTML/CSS structure!