文本对齐在更改HTML中的宽度时发生更改 [英] Text-Align changes when changing width in HTML
问题描述
我希望我的文本以40%的宽度居中。在我最后一个代码示例中,一切都是完美的,但文本在< p>
元素下似乎是10px。
I want my Text to be centered with a width of 40%. In my last example of code everything is perfect but the text appears to be like 10px under the <p>
element.
没有宽度40%:
<p id="pname" style="text-align:center; color:white;overflow:hidden;text-overflow: ellipsis;white-space: nowrap;">
Some really long text in here
</p>
- >文字宽度为40%,但不居中
--> Text has a width of 40% but is not centered
使用宽度40%:
<p id="pname" style="text-align:center; width:40%;color:white;overflow:hidden;text-overflow: ellipsis;white-space: nowrap;">
Some really long text in here
</p>
- >文字似乎有一个text-align:left
--> Text appears to have a text-align:left
使用display:inline-block:
With display:inline-block:
<p id="pname" style="display:inline-block;text-align:center; width:40%;color:white;overflow:hidden;text-overflow: ellipsis;white-space: nowrap;">
Some really long text in here
</p>
- >文本正确对齐,宽度完全为40%,但文本出现在< p>
--> The text is aligned correctly and perfectly 40% width but the Text appears under the <p>
我失踪了什么?提前感谢!
What am i missing? Thank you in advance!
推荐答案
要使CSS中的块级元素居中,必须添加 :0 auto;
因为 text-align:center
仅影响文本和 inline
To center a block level element in CSS, you have to add margin:0 auto;
because text-align:center
affects text and inline
elements only.
p {
margin: 0 auto; /* center element horizontally */
text-align: center;
width: 40%;
color: white;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
background:#666;
}
body { background:#000; }
<p id="pname">Some really long text in here</p>
这篇关于文本对齐在更改HTML中的宽度时发生更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!