how to center a div?
- User
how to 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 to center a div?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
There are several ways to center a div, depending on whether you want to center it horizontally, vertically, or both. Here are the most common and effective methods:
.parent {
display: flex;
justify-content: center; /* horizontal centering */
align-items: center; /* vertical centering */
height: 100vh; /* or any specific height */
}
.child {
/* child div content */
}
.parent {
display: grid;
place-items: center;
height: 100vh;
}
.child {
/* child div content */
}
.parent {
position: relative;
height: 100vh;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.child {
width: 300px; /* must have a defined width */
margin: 0 auto;
}
.parent {
text-align: center;
}
.child {
display: inline-block;
}
.parent {
display: table;
width: 100%;
height: 100vh;
}
.child {
display: table-cell;
vertical-align: middle;
text-align: center;
}
<div class="container">
<div class="centered-div">
Centered Content
</div>
</div>
.container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.centered-div {
background: #f0f0f0;
padding: 20px;
border-radius: 8px;
}
.container {
display: grid;
place-items: center;
min-height: 100vh;
}
.centered-div {
width: 400px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px; /* half of height */
margin-left: -200px; /* half of width */
}
For modern web development, flexbox is typically the go-to solution because it's well-supported, flexible, and handles dynamic content well.