Html 居中对齐 div 内的“跨度”文本

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

Center align "span" text inside a div

htmlcss

提问by testndtv

I have a HTML code as;

我有一个 HTML 代码;

<div class="left">
<span class="panelTitleTxt">Title text</span>
</div>

My CSS is as follows;

我的 CSS 如下;

.left {
    background-color: #999999;
    height: 50px;
    width: 24.5%;
}
span.panelTitleTxt {
                display: block;
                width: 100%;
                height: 100%;
}

Now how do I center align the span text inside the div? (Assume that the "left" div after the % conversion gets a px width of 100px)

现在如何将 div 内的跨度文本居中对齐?(假设%转换后的“左”div得到100px的px宽度)

I tried the standard way of using margin:auto, but that is not working.

我尝试了标准的使用方式margin:auto,但这不起作用。

Also I want to avoid using text-align:center.

我也想避免使用text-align:center.

Is there some other way of fixing this?

有没有其他方法可以解决这个问题?

回答by Lee

You are giving the span a 100% width resulting in it expanding to the size of the parent. This means you can't center-align it, as there is no room to move it.

你给跨度一个 100% 的宽度,导致它扩展到父级的大小。这意味着您无法将其居中对齐,因为没有空间可以移动它。

You could give the span a set width, then add the margin:0 autoagain. This would center-align it.

您可以为跨度设置一个宽度,然后margin:0 auto再次添加。这将使它居中对齐。

.left 
{
   background-color: #999999;
   height: 50px;
   width: 24.5%;
}
span.panelTitleTxt 
{
   display:block;
   width:100px;
   height: 100%;
   margin: 0 auto;
}

回答by Cuse70

If you know the width of the span you could just stuff in a left margin.

如果您知道跨度的宽度,您可以只填充左边距。

Try this:

尝试这个:

.center { text-align: center}
div.center span { display: table; }

.center { text-align: center}
div.center span { display: table; }

Add the "center: class to your .

将“center: class 添加到您的 .

If you want some spans centered, but not others, replace the "div.center span" in your style sheet to a class (e.g "center-span") and add that class to the span.

如果您希望某些跨度居中,而不是其他跨度,请将样式表中的“div.center span”替换为一个类(例如“center-span”)并将该类添加到该跨度中。