Html 如何在 CSS 中将 span 元素居中?

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

How to center a span element in CSS?

htmlcss

提问by Ashwin

I have three <span>elements that I want to place horizontally one after the other. I also need the middle element to be at the center of the page (horizontally), but margin:auto; width: 100pxis not working since it is a <span>. If I make it <div>, there is a line break.

我有三个<span>要一个接一个水平放置的元素。我还需要中间元素位于页面的中心(水平),但margin:auto; width: 100px由于它是<span>. 如果我成功了<div>,就会有一个换行符。

How do I solve this problem?

我该如何解决这个问题?

回答by Albert Xing

I would use three identical spanelements of 100px width, with display: inline-blocknested inside a divwith text-alignset to center: http://jsfiddle.net/e9sru/

我将使用三个相同的span100像素宽的元素,具有display: inline-block嵌套的内侧的divtext-align设置为中心:http://jsfiddle.net/e9sru/

HTML:

HTML:

<div id="container">
    <span class="inner">
        <div class="overflow">Lorem ipsum dolor est mori. I am overflowing but still to the left of number two</div>
    </span>
    <span class="inner">Two</span>
    <span class="inner">Three</span>
</div>

CSS:

CSS:

#container {
    text-align: center;
}

.inner {
    display: inline-block;
    position: relative;
}

.overflow {
    float: right;
}

回答by sam_7_h

If you create one div and set that to have a width of 100%. Inside this dive you create 3 more divs; one for each element. If you set each element to have a width of 33.3% then it will centre the middle one and the other 2 accordingly. Like wise you can add margins to decrease the 33.3%. For example margin: 0 3% 0 3% on the centre div would give it 3% margin on the left and right. Minus 6% from the size of the div width as it must always total 100%

如果您创建一个 div 并将其设置为 100% 的宽度。在这次潜水中,您再创建 3 个 div;每个元素一个。如果您将每个元素设置为 33.3% 的宽度,那么它将相应地将中间的一个和其他 2 个居中。同样明智的是,您可以添加边距以减少 33.3%。例如 margin: 0 3% 0 3% on the center div 会在左边和右边给它 3% 的边距。从 div 宽度的大小减去 6%,因为它必须始终为 100%

回答by HymanJoe

spanis an inline element, so it doesn't behave like a divwhich is a block element.

span是一个内联元素,所以它的行为不像div一个块元素。

I suggest doing a mix of floats and align center.

我建议混合使用浮动和对齐中心。

Example:

例子:

HTML

HTML

<span class="block element3">ELEMENT3</span>
<span class="block element1">ELEMENT1</span>
<span class="block element2">ELEMENT2</span>

CSS

CSS

.block {
    display: block;
    width: 100px;
}
.element3 {
    float: right;
    background-color: red;
}
.element2 {
    float: left;
    background-color: green;
}
.element1 {
    text-align: center;
    background-color: blue;
    width: auto;
}

UPDATE:

更新:

http://jsfiddle.net/YUCv2/1/

http://jsfiddle.net/YUCv2/1/