简体   繁体   English

如何在CSS中调整div框的大小,以使文本居中而不管其长度如何

[英]How to size a div box in CSS so text is centered regardless of length

I find it difficult to express the question in words since I'm not knowledgeable enough about CSS. 我发现很难用语言表达问题,因为我对CSS不够了解。 So, I've made two example jsfiddles. 因此,我制作了两个示例jsfiddles。

In this first example we see how the output shows a left aligned text. 在第一个示例中,我们看到输出如何显示左对齐的文本。 http://jsfiddle.net/Aro2220/yw38p/ http://jsfiddle.net/Aro2220/yw38p/

But in this second example we see that when the text is long enough it fills the entire width of the frame (not sure if that's the correct term) and centers nicely all the way down. 但是在第二个示例中,我们看到当文本足够长时,它会填满框架的整个宽度(不确定这是否是正确的术语),并且会一直向下居中。 http://jsfiddle.net/Aro2220/DUcP6/ http://jsfiddle.net/Aro2220/DUcP6/

I am trying to get the text to be perfectly centered in that frame regardless of length. 我正在尝试使文本在长度上完全居中,而无论其长度如何。 How can I do this? 我怎样才能做到这一点? My CSS is pretty sparse and I'm not sure if there's a CSS command I'm missing that does this easily or if this is a complicated task. 我的CSS非常稀疏,我不确定是否缺少一个CSS命令可以轻松做到这一点,或者这是一项复杂的任务。

#outer {
    position: absolute;
    overflow: hidden;
    height: 200px;    
}

#inner {
   position: relative;  
   top: 0px;    
   text-align: center;
}

use this Demo1 Demo2 使用此Demo1 Demo2

this will do the trick 这将达到目的

#outer {
    position: absolute;
    overflow: hidden;
    height: 200px;
    width:100%; // added this to make the outer div width 100%
}

Suggested by sfjedi sfjedi建议

if you have issues w/ margins and/or padding giving you an unwanted horizontal scrollbar , use css box-sizing: border-box so the 100% width doesn't throw you off 如果您在w/ margins和/或padding有问题,从而给您不必要的horizontal scrollbar ,请使用css box-sizing: border-box这样100% width不会使您失望

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM