A joke among CSS/HTML designers is how difficult it is to simply center an item either vertically or horizontally. As simple as this sounds, there isn’t a simple “position: center” type field in CSS. In simple cases you could simply add a 25% margin to the left side of the object, which will take 25% of the width of the outer element (or the page if none) and push the element that much from the left. Of course, that only works in simple cases.
If you wanted to use a different positioning method or wanted to have another element on the left or right of the centered element it would break.There are many different ways to center an element, each with their own pros and cons. There are so many, in fact, that someone even created a website to help you find the best method for your use case: http://howtocenterincss.com/.
I recently learned about a new multi-purpose display trick in CSS for positioning and sizing elements, called flexboxes. To use them, you would declare an outer div element as a flexbox (display: flex), making all of it’s children follow the flex settings. One of my favorite features of flexboxes is the fact that you can apply all of these settings in the wrapping element instead of doing it on each individual element. For a use case, we’ll assume a navigation bar.
FIrst, let’s say the outer wrapper’s width goes across the entire page, and the height is relative to the elements inside. Each inside element is a simple box with padding, text, and a background. You want them to display as elements side by side, in the center, with space between each one. All of those effects can be applied in the outer flexbox, without having to touch the buttons.
All you have to do to center the buttons is apply the justify-content: center field. If you wanted one button to be larger than the rest, but only by a percentage of the rest, you can use flex-grow on the specific element. By default, it’s “1”. This basically tells the element to take up as much space as one element in that flexbox.
If you set it to 2, it will be twice as large as the other elements. This is extremely helpful when you have to deal with a changing navigation bar, as you don’t have to worry about things breaking when buttons are added or removed.