Centering elements

Sometimes, centering elements while trying to use a content-dependent width can be a real pain in the… you get it, no? The tried and tested way of centering elements while still having control over their dimensions, paddings and margins will be declaring them as block-level element, but that comes some disadvantages. Meanwhile, using inline-elements are completely irrelevant as you cannot dictate their dimensions.

Block level element

Block level element always takes up the available width in its containing parent. Auto (content-based) width is not possible via CSS, but you can specify explicit width. You can center align the text, but not force the width to collapse to the size of its content.

Inline level element

As an inline-level element, it will resist various CSS properties, such as vertical margins and paddings, setting explicit widths.

But wait!

There is a way of using inline-block elements, and some handy CSS tricks than can actually achieve both content-dependent width and horizontally-centered alignment:

Inline-block level element

Auto (content-based) width is possible, but requires text-align: center in parent to be centered, which can be inconvenient and requires additional nesting if you don't want to affect alignment of texts in the same node. However, you can use relative positioning and CSS transform to make it work!

Simply position the element relatively, and use a left offset of 50%, followed by a CSS transformation to translate it back to the left by half of its own width:

[selector] {
    position: relative;
    left: 50%;
    transform: translateX(-50%);
}