【问题标题】:Centering text vertically as it grows, in child class在子类中随着文本的增长垂直居中
【发布时间】:2012-12-13 10:55:37
【问题描述】:

我有一个父容器(如弹出窗口),其中我有一个子元素附加到父容器。子元素是一个包含一些文本的 div。我想将 div 内的文本居中,以便文本在子 div 中保持居中对齐,但文本应在超过 3-4 行时垂直对齐。我能够随着文本的增长垂直对齐文本,但是当它仍然是一个小文本时,它应该垂直居中,这不会发生。我在子类中尝试了很多 css 属性。 任何帮助都会很好。

.parentclass {
  position: absolute;
  top: 110px;
 left: 165px;
 width: 470px;
 height: 260px;
 text-align: center;
 background-image: url(../images/Notification_BG.png); }

.childclass {
 position: relative;
 position: inherit;
 width: 430px;
 height: 192px;
 left: 50%;
 top: 50%;
 margin-left: -215px;
 margin-top: -96px; /* Negative half of height. */
 text-align: center;
 text-overflow: -o-ellipsis-lastline;
 border: 1px solid blue;
 font-family: Arial;
 font-size: 28px;
 color: white; }

谢谢 KK

【问题讨论】:

标签: javascript css


【解决方案1】:

你用过vertical-align:middle;吗?

试试这个:

.childclass { 显示:表格单元格; 垂直对齐:中间; 文本对齐:居中; }

这个链接一定会对你有所帮助:

vertically-center-text-in-a-100-height-div

【讨论】:

  • 我确实用过这些css属性,但是好像不行。我需要在opera浏览器上使用我的解决方案。
  • 任何其他建议。在这种情况下,表格属性可能不起作用。
  • 我在很多情况下都使用过它,它对我有用。你删除了 position relative , top , left 等等,尝试删除它们并使用 display:table-cell;告诉我它是否有效。
  • 是的表格单元格正在工作,但我希望文本进入 2 行,现在文本开始非常靠近边框,我希望它从左边框开始有一些间距。应该如何这会发生吗?
  • 给 .childclass{padding-left: 20px;}
【解决方案2】:

将父类显示为表格,子类显示为表格单元格,vertical-align:middle 肯定可以工作

html

<div class='parentclass'>
<div class='childclass'>Text which is more than two or three lines</div>
</div>

CSS

.parentclass {
 height: 260px;
 text-align: center;
 display:table;
}
.childclass {
 vertical-align: middle;
 width: 430px;
 top: 50%;
 text-align: center;
 text-overflow: -o-ellipsis-lastline;
 border: 1px solid blue;
 font-family: Arial;
 font-size: 28px;
 color: black; 
}

See this fiddle for demo

【讨论】:

  • 是的,您的带有 Table-cell 的子类正在工作,但我希望文本分 2 行显示,现在文本开始非常靠近边框,我希望它从左边框开始有一些间距.
  • 使用文本缩进:20px;子类的 css 中的属性来获得你想要的东西
  • @Dinesh...谢谢这有效...现在我正在尝试实现...如果文本通过使用 CSS max-height 属性扩展超出图形区域 ieParentclass 的高度,则文本应截断使用 CSS 属性 text-overflow: -o-ellipsis-lastline;...我也在这方面发现问题...任何想法:)
猜你喜欢
  • 2013-10-15
  • 2015-09-16
  • 1970-01-01
  • 1970-01-01
  • 2012-09-17
  • 2013-02-01
相关资源
最近更新 更多