How do I center a div?
Centering a div element is a very common task in web development. There are several effective methods, and the best one to use often depends on the context.
margin: autoThis is the classic method for centering a block-level element horizontally.
div must have a defined width.margin: auto distributes remaining horizontal space equally.CSS Example:.centered-div { width: 50%; margin: 0 auto; }
Flexbox makes centering (both horizontally and vertically) incredibly easy.
display: flex;justify-content: center; (Horizontal)align-items: center; (Vertical)CSS Grid is a powerful system that excels at centering with very little code.
place-items shorthand on the parent.display: grid;place-items: center;Useful for centering an element that is removed from the normal document flow.
position: relative;.position: absolute; top: 50%; left: 50%;.transform: translate(-50%, -50%); to shift it back to the true center.margin: auto.Note: text-align: center; centers inline content (text/images) but not the div container itself.