Is it possible to center an inline-block element and if so, how?

懵懂的女人 提交于 2019-11-27 03:19:21

Simply set text-align: center; on the container.

Here's a demo.

Another way to do this (works for block element also):

.center-horizontal {
     position: absolute;
     left: 50%;
     transform: translateX(-50%);
}

Explanation: left:50% will position the element starting from the center of containing parent, so you want to pull it back by half of its width with transform: translateX(-50%)

Note1: Be sure to set the the position of containing parent to position: relative; if the parent is absolutely positioned put a 100% width and height, 0 padding and margin div inside it and give it position: relative

Note2: Can also be modified for vertical centering with

top:50%;
transform: translateY(-50%);

A little late, but similar to Ivek's answer, you can avoid using the position declaration by using margin-left rather than left, so:

margin-left: 50%; transform: translateX(-50%);

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!