【问题标题】:CSS : alternative to vertical-align?CSS:替代垂直对齐?
【发布时间】:2013-11-22 19:29:20
【问题描述】:

有没有替代垂直对齐的方法?

为了使用垂直对齐,我必须将显示设置为表格单元格。当我将显示设置为表格单元格时,我设置的 div 的高度不起作用。我在那个 div 上设置了溢出-y 为自动。我想要做的是从该 div 的底部对齐 div 内的内容......我无法做到这一点..还有其他选择吗?

这就是我现在拥有的:

#container{
height:375px;
border:1px solid #000;
position:relative;
overflow-y:auto;
display:table-cell;
vertical-align:bottom;
}

#container > div{
margin:0;
margin-bottom:5px;
width:660px;
position:relative;
}

【问题讨论】:

  • 使用显示:块;和填充,边距。
  • 如果您发布您的代码,我们可以vertical-align 工作:) 您也可以使用绝对定位或填充。

标签: html css


【解决方案1】:

有两种选择,一种是设置line-height..,另一种是将父元素设置为position: relative;,然后将子元素设置为position: absolute;,之后使用top: 50%;和@987654326 @ 并且减去边距,这将是 absolute 元素本身的 heightwidth 总数的 1/2...

.parent {
   position: relative;
}

.child {
   position: absolute;
   top: 50%;
   left: 50%;
   margin-top: -100px; /* Assuming height of the element is 200 */
   margin-left: -200px; /* Assuming width of the element is 400 */
}

这里有一个问题,使用absolute 将需要您尝试垂直align 的元素的固定尺寸center


使用display: table-cell;垂直对齐元素

Demo

.parent {
    height: 200px;
    background: #eee;
    display: table-cell;
    width: 300px;
    vertical-align: bottom;
}

.child {
    height: 20px;
    background: #aaa;
}

如果你使用display: table;作为包装元素会更好。

【讨论】:

  • 我会这样做.. 但问题是容器内有多个 div...
  • 您在 jsfiddle 演示中提供的代码运行良好.. 感谢您的回答..
  • 当容器内的内容变高时,容器也会随之变高,尽管我将它设置为溢出:自动..知道如何处理这个问题吗?
  • @user1763032 如果可能的话,你可以提出另一个关于该问题的问题和小提琴:)
【解决方案2】:

试试这个:

#container{
height:375px;
line-height:375px;
}

#container > div{
display:inline-block;
line-height:1;
}

【讨论】:

  • 这是唯一能正确模仿“table-cell”的“hack”,因为它适用于任何长度的文本。
猜你喜欢
  • 1970-01-01
  • 2015-09-06
  • 2011-10-03
  • 1970-01-01
  • 2011-06-12
  • 2010-10-23
  • 2011-06-14
相关资源
最近更新 更多