CSS Align
By Tony 8.3.2024
Aligning things is important. No matter if it's a building, furnitures at your house, images on a website, or anything, we always align stuff to keep things organized and simple. We've already covered aligning text with text-align: center, but what if you want to align an image to the center? Or a div element? We'll do that in this tutorial.
background-color: lightblue;
width: 50px;
margin-inline: auto;
We added background-color and width just for you to visualize and see the element better. The main property that actually aligns the element here is margin-inline: auto. When you set the margin of something to "auto", the browser tries to give the element as much margin as possible that still fits on the page. This results in equal maximum margin on the left and the right side of the element (margin-inline property), making the element aligned in the center. You can also use margin-left: auto; to give maximum margin to only the left side of the element, thus aligning it to the right of the page. Try it out yourself below!
As in the example above, the <p> element is properly aligned to the center of the screen using the margin-inline: auto CSS rule. Note that this technique only works on HTML block elemenets, not inline elements, so set the inline elements to display: block if you want to use this technique to align elements to the center.