我有一个固定大小的框,里面有两个元素,一个图像和一些文本。两者的宽度和高度都是可变的,我试图在图像下方的剩余空间内垂直对齐文本。
|-------- 184px --------|
(text-align:center)
+-----------------------+ - -
| +-------+ | | |
| |#######| | | |
| |#######| | | | ?
| |#######| | | 1 |
| +-------+ | | 6 |
| - - - - - - - - - - - | | 8 -
| | | p |
| Some vertically | | x |
| aligned text with | | | *
| variable length | | |
| | | |
+-----------------------+ - -
line-height
不能使用,因为文本最多可以有三行vertically-align
似乎只适用于固定的height
- JavaScript 始终为
img
返回height:0
(无论如何首选纯 CSS 解决方案)
HTML:
<div class="box boxed js-box">
<img src="/images/box-icon1.png">
<span class="text short js-box-text">
Title
</span>
<span class="text long js-box-text">
Detailled description when hovered
</span>
</div>
风格:
.box {
background: #FFF;
cursor: default;
height: 168px;
margin-top: 30px;
padding: 4px;
text-align: center;
width: 184px;
}
.box img {
border: 0;
display: block;
margin: auto;
margin-bottom: 24px;
position: relative;
top: 16px;
width: 76px;
}
.box .text {
bottom: 4px;
font-size: 12px;
position: relative;
}
.box .text.short {
font-size: 16px;
top: 8px;
}
.box .text.long {
display: none;
font-size: 14px;
}
最佳答案
最简单的是在父元素和子元素上使用显示类型 table 和 table-cell/row:
尝试添加:
.box {
display: table;
}
.box .text {
display: table-row;
vertical-align: middle;
}
现在 vertical-align: middle 适用于那些! 请注意,在某些情况下,您不想直接在父级或子级上显示表格。您可以只添加一个包装器 div,其中包含您想要垂直布局的内容。
可能需要将文本再次放入表行内的表单元格显示包装器中。我不确定那个 atm。
关于javascript - 垂直对齐和具有动态内容和高度的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27439563/