CSS 是否可以将内联块元素居中,如果可以,如何居中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7601678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 01:46:15  来源:igfitidea点击:

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

cssmathjax

提问by Deets McGeets

I have an element of initially unknown width, specifically a MathJax equation supplied by the user. I have the element set as inline-block to ensure that the width of the element fits its contents and so that it has a defined width. However, this prevents traditional methods of centering. That is, the following does not work:

我有一个初始宽度未知的元素,特别是用户提供的 MathJax 方程。我将元素设置为 inline-block 以确保元素的宽度适合其内容并具有定义的宽度。然而,这阻止了传统的居中方法。也就是说,以下操作不起作用:

.equationElement
{
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
}

And the solution cannot be:

解决方案不能是:

.equationElement
{
    display: block;
    width: 100px;
    margin-left: auto;
    margin-right: auto;
}

Because I have no idea what the width should actually be beforehand and if the user clicks on the equation, I need the entire equation highlighted, so I cannot set the width to 0. Does anyone have a solution to centering this equation?

因为我事先不知道宽度实际上应该是多少,如果用户点击方程,我需要突出显示整个方程,所以我不能将宽度设置为 0。有没有人有解决这个方程居中的方法?

回答by phihag

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

只需设置text-align: center;在容器上。

Here's a demo.

这是一个演示

回答by Ivek

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 startingfrom the center of containing parent, so you want to pull it backby half of its width with transform: translateX(-50%)

说明: left:50% 将从包含父元素的中心开始定位元素,因此您希望使用 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

注意1:一定要将包含父级的位置设置为position:relative;如果父级绝对定位,则在其中放置 100% 宽度和高度、0 填充和边距 div 并为其指定位置:相对

Note2: Can also be modified for vertical centering with

注2:也可以修改为垂直居中

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

回答by Amie Wilt

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

有点晚了,但类似于 Ivek 的回答,您可以position通过使用margin-left而不是来避免使用声明left,因此:

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

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