Tuesday, March 9, 2021

Centering horizontally and vertically

<div id="parent">
    <div id="child">hello world</div>
</div>
Centering with margin, it has to be done at child level:
#parent {
    width: 50vw;
    height: 50vh;
    background-color: gray;
    display: flex;
}
#child {
    margin: auto; 
}
Try it at: https://jsfiddle.net/xd7uwgn8/

It's better if it is done at the parent level, the parent should be able to control the child elements:
#parent {
    width: 50vw;
    height: 50vh;
    background-color: gray;
    
    display: flex;
    justify-content: center;
    align-items: center;
}
#child {
}
Try it at: https://jsfiddle.net/xd7uwgn8/2/

Another good thing if it is done at parent level, creating unnecessary div+margin:auto for the content could be avoided:
<div id="parent">
    hello world
</div>
Try it at: https://jsfiddle.net/xd7uwgn8/3/

No comments:

Post a Comment