There are four way to align div horizontally and vertically center
1 - margin
2 - position
3 - flex
4 - grid
Align div by margin property
Horizontally align div with css margin property and it not align div in vertically center
<html>
<head>
<style>
#parent-div{
margin:20px;
width:400px;
height:150px;
border:1px solid black;
}
#child-div{
width:80px;
height:80px;
border:1px solid blue;
margin:0 auto;
}
</style>
</head>
<body>
<div id='parent-div'>
<div id='child-div'></div>
</div>
</body>
</html>
Align div by position property
Div align center with horizontally and vertically by css position property
<html>
<head>
<style>
#parent-div{
margin:20px;
width:400px;
height:150px;
border:1px solid black;
position:relative;
}
#child-div{
width:80px;
height:80px;
border:1px solid blue;
top:50%;
left:50%;
transform:translate(-50% ,-50%);
position:absolute;
}
</style>
</head>
<body>
<div id='parent-div'>
<div id='child-div'></div>
</div>
</body>
</html>
Align div center by flex property
flex property use to align div horizontally and vertically center . flex is easy method above two align method
Note : when align div by css flex property , you need to apply flex property to its parent div
<html>
<head>
<style>
#parent-div{
margin:20px;
width:400px;
height:150px;
border:1px solid black;
/* flex property apply */
display:flex;
justify-content:center; /* use for horizontally center */
align-items:center; /* use for vertically center */
}
#child-div{
width:80px;
height:80px;
border:1px solid blue;
}
</style>
</head>
<body>
<div id='parent-div'>
<div id='child-div'></div>
</div>
</body>
</html>
Align div center by grid property
Css grid also use to align div center from vertically and horizontally
Note : when align div by css grid property , you need to apply grid property to its parent div like css flex property
<html>
<head>
<style>
#parent-div{
margin:20px;
width:400px;
height:150px;
border:1px solid black;
/* grid property apply */
display:grid;
justify-items:center; /* use for horizontally center */
align-items:center; /* use for vertically center */
}
#child-div{
width:80px;
height:80px;
border:1px solid blue;
}
</style>
</head>
<body>
<div id='parent-div'>
<div id='child-div'></div>
</div>
</body>
</html>
Learn more artical related to Web Dev also visit
Top comments (4)
Just a heads up that you can add highlighting to the code blocks if you'd like. Just change:
... to specify the language:
More details in our editor guide!
I write code inside
usefull for javascript code
No the syntax highlighting works for all programming/markup languages Markdown Extended Syntax.
Using your first code snippet as an example:
Use backticks I only used quotes below to stop it from turning into a code block.
'''html
'''
Thanks Andrew Baisden