r/css • u/void5253 • May 13 '23
Help understanding why this is centering the div?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Learning how to center</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="box">
</div>
</body>
</html>.box {
background-color: #ECCDB4;
height: 300px;
width: 200px;
position: fixed;
margin: auto;
inset: 0;
}I am just not getting why position, margin, inset when used as above center the div.
0
Upvotes
3
u/madovermoto May 13 '23
It's due to
Comment that line and try again? Read more about position property in css here
https://developer.mozilla.org/en-US/docs/Web/CSS/position
If you want to center a div with position fixed, you need to give
5
u/Kcilc May 13 '23 edited May 13 '23
Here's my understanding of what's going on:
inset: 0).The reason
margin: autodoesn't center a block-level element vertically is simply because there is no leftover vertical space in that situation.3
u/raccoonrocoso May 13 '23
When you use
position:fixedyou're effectively removing that container from the rest of the document flow. Settingmargin:autoon an element will automatically create equal distance between left and right.inset:0is shorthand for sayingleft:0right:0top:0bottom:0Since the width of
.boxis explicitly set. And the margin is set to auto., and you're assigning this class to a div. Because the class is assigned to a div. By default the box will inherit thedisplay:block. Thus, the final result will be a centered div with a colored background.Depending on what you want to do. There are multiple different approaches. Either set margin to something like (
margin:0px 0px 0px auto) or remove (inset:0) and just use (left:0).I'd suggest using a parent with flexbox to control the position of the child div.