使用 CSS 的文本居中在 IE 中不起作用

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

Text Centering Using CSS not working in IE

cssinternet-explorercentertext-align

提问by Shady Studios

I am having problems getting text within a table to appear centered in IE.

我在获取表格中的文本以在 IE 中居中显示时遇到问题。

In Firefox 2, 3 and Safari everything work fine, but for some reason, the text doesn't appear centered in IE 6 or 7.

在 Firefox 2、3 和 Safari 中一切正常,但由于某种原因,文本在 IE 6 或 7 中没有出现居中。

I'm using:

我正在使用:

h2 {
  font: 300 12px "Helvetica", serif; 
  text-align: center; 
  text-transform: uppercase;
}

I've also tried adding margin-left:auto;, margin-right:autoand position:relative;

我也试过添加margin-left:auto;,margin-right:autoposition:relative;

to no avail.

无济于事。

采纳答案by Bloodhound

The table cell needs the text-align: center.

表格单元格需要 text-align: center。

回答by Alex Achinfiev

CSS text-align property should be declared on the parent element and not the element you are trying to center. IE uses text-align: center property to center text. Firefox uses margin: 0 auto and it has to be declared on the element you are trying to center.

CSS text-align 属性应在父元素上声明,而不是在您试图居中的元素上声明。IE 使用 text-align: center 属性来居中文本。Firefox 使用 margin: 0 auto 并且它必须在您尝试居中的元素上声明。

<div style="text-align: center">
    <h2 style="margin: 0 auto">Some text</h2>
</div>

回答by dawnerd

Might be a typo, but you are missing a semicolon here:

可能是一个错字,但你在这里缺少一个分号:

margin-left:auto; margin-right:auto position:relative;

Should be:

应该:

margin-left:auto; margin-right:auto; position:relative;

If that doesn't work, make sure the element you are trying to center the text on has some width. Try setting the width to 100% and see if anything changes.

如果这不起作用,请确保您尝试将文本居中的元素具有一定的宽度。尝试将宽度设置为 100%,看看是否有任何变化。

回答by Rahi.Shah

If you can/want to use flexbox, you can use the following as well.

如果您可以/想要使用 flexbox,您也可以使用以下内容。

display: flex;
justify-content: center;
align-items:center

回答by nickf

The text-align: centershould be sufficient, since you're centering the text inside a block element (h2) - adjusting the margins will change the position of the block, not the text.

text-align: center应该是足够的,因为你定心块元素(H2)内的文本-调整空间将改变块的位置,而不是文字。

I wonder if it's just that IE is having a dummy-spit at that fontdeclaration you've got there?

我想知道是否只是 IE 对font你的声明有一个假吐槽?

回答by 1077

Use text-align:center in the div/td that surrounds the h2.

在围绕 h2 的 div/td 中使用 text-align:center。

<table style = "width:400px;border:solid 1px;">
    <tr>
        <td style = "text-align:center;"><h2>hi</h2></td>
    </tr>
</table>

edit: wow, stackoverflow's community is pretty fast!

编辑:哇,stackoverflow 的社区非常快!