center a
DIV
<div class="outside">
<div class="inside"></div>
</div>
.outside {
width: 400px;
height: 400px;
background-color: #ccc;
display: flex;
align-items: center;
justify-content: center;
}
.inside {
background-color: pink;
height: 200px;
width: 200px;
}
<div class="outside">
<div class="inside">inside</div>
</div>
.outside {
width: 400px;
height: 400px;
background-color: #ccc;
display: flex;
}
.inside {
background-color: pink;
margin: auto;
height: 200px;
width: 200px;
}
.element {
max-width: fit-content;
margin-left: auto;
margin-right: auto;
}
Besides the method above, you can also set margin-left and right to auto, so the browser will automatically center the element specified.
<div class="outside">
<div class="inside">inside</div>
</div>
.outside {
display: grid;
place-content: center;
}
<div class="outside">
<div class="inside">inside</div>
</div>
.outside {
width: 400px;
height: 400px;
background-color: #ccc;
position: relative;
}
.inside {
background-color: pink;
height: 200px;
width: 200px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.element {
position: fixed;
inset: 0px;
margin: auto;
}
<div class="outside">
<div class="inside">inside</div>
</div>
.outside {
width: 400px;
height: 400px;
background-color: #ccc;
text-align: center;
}
.inside {
background-color: pink;
line-height: 400px;
}
Method | Chrome | Firefox | Safari | Edge |
---|---|---|---|---|
Using flexbox | Yes | Yes | Yes | Yes |
Using flexible display | Yes | Yes | Yes | Yes |
Using margin-inline | Yes | Yes | Yes | Yes |
Using grid | Yes | Yes | Yes | Yes |
Using absolute positioning | Yes | Yes | Yes | Yes |
Using the browser window | Yes | Yes | Yes | Yes |
Using text-alignment | Yes | Yes | Yes | Yes |