This quick tutorial will help you center elements (like an image or a block) using CSS.
Method #1
- Set your element to Display: Inline-Block
- Set the parent element to Text-Align: Center.
- Done!
Pros: Perfect if you want all the elements inside of the parent element to be centered, so only has to be done once.
Cons: You have to set styles on the parent element instead of just the element.
Additional Info: When you set an element to Display: Inline Block, the width of the element is automatically calculated by the contents of the element. So if it’s an image it will be the width of the image or if it’s a text element the width will become as wide as the text is. With the Inline Block setting you can stack elements right next to each other as well. If you don’t want elements to stack next to each other you will have to set some or all of the elements to be Display: Block, which stack on top of each other instead of next to each other. If you are trying to center typography just align your text to center.
Method #2
- Set your element to Display: Block
- Set left and right margins to auto.
- Set a width on the element.
- Done!
Pros: In this method you only have to add CSS to the element, not the parent element as well.
Cons: You have to set a width on the element (pixels or percent width). Not good for text elements.
Additional Info: When you set an element to Display: Block the width of the element becomes 100% by default, so it will expand the full width of the parent element. This is obvious with buttons and blocks, but not so obvious with text and images. Block elements stack on top of each other. They do not stack next to each other like Inline-block elements if their widths are small enough to fit next to each other in the parent element. The way to make block elements stack next to each other is to use Method 1 or to use Float left or right, but it’s not possible to center floated elements without doing more complex layout stuff.