Html 对齐内联块中心

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26657918/
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-29 02:58:34  来源:igfitidea点击:

Aligning inline-block center

htmlcentercenteringcss

提问by Andrew

What would be the easiest way to center align an inline-block element?

居中对齐内联块元素的最简单方法是什么?

Ideally, I don't want to set a width to the elements. This way depending on the text inputted within the elements, the inline-block element will expand to the new width without having to change the width within the CSS. The inline-block elements should be centered on top of one another (not side by side), as well as the text within the element.

理想情况下,我不想为元素设置宽度。这种方式取决于元素中输入的文本,内联块元素将扩展到新的宽度,而无需更改 CSS 中的宽度。inline-block 元素应该以彼此为中心(而不是并排),以及元素内的文本。

See code below or see on jsFiddle.

请参阅下面的代码或查看jsFiddle

The current HTML:

当前的 HTML:

<div>
  <h2>Hello, John Doe.</h2>
  <h2>Welcome and have a wonderful day.</h2>
</div>

The current SCSS:

当前的 SCSS:

@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,300,600);  

body {
    margin: 0 auto;
    background: rgba(51,51,51,1);
    font-family: 'Open Sans', sans-serif;
}

div {
    width: 100%;
    height: auto;
    margin: 15% 0;
    text-align: center;
    h2 {
        margin: 0 auto;
        padding: 10px;
        text-align: center;
        float: left;
        clear: left;
        display: inline-block;
        &:first-child {
            color: black;
            background: rgba(255,255,255,1);
        }
        &:last-child {
            color: white;
            background: rgba(117,80,161,1);
        }
    }
}

Adding a br between the two elements and taking out the float: left/clear: left may be the easiest way; however, I was curious if there was another way going about this.

在两个元素之间添加一个 br 并取出 float: left/clear: left 可能是最简单的方法;然而,我很好奇是否有另一种方式来解决这个问题。

回答by k-nut

Like this? http://jsfiddle.net/bcL023ko/3/Remove the float:leftleft and add margin: 0 autoto center the element. Or is it something else that your are looking for?

像这样?http://jsfiddle.net/bcL023ko/3/删除float:left左边并添加margin: 0 auto到中心元素。或者它是您正在寻找的其他东西?