通过css将页眉标签与固定高度垂直对齐页眉、高度、标签、css

2023-09-03 10:39:02 作者:红颜多薄命じ

我有一个固定宽度的Header标记,它在某些情况下将包含2行文本,在某些情况下是1行。我希望它们垂直居中对齐,就好像填充已经被计算出来弥补了这一点一样。

我希望在不修改加价的情况下实现这一点。

<h1>This would be 2 lines of text</h1>
<h1>This is 1 line</h1>
<h1>This would be 2 lines of text</h1>
<h1>This is 1 line</h1>
<h1>This would be 2 lines of text</h1>
<h1>This is 1 line</h1>
<h1>This would be 2 lines of text</h1>
<h1>This is 1 line</h1>

css:

h1 {
float:left;
margin:5px;
padding:5px;
width:100px;
height:50px;
vertical-align:middle; /*obvi doesn't work because it's not an inline element */
text-align:center;
background:#336699;
color:#fff;
}
excel中如何将工作表标签设置为页眉

也许...就像一个基于自动高度确定两个不同填充属性的css选择器?例如,如果我将高度设置为AUTO,如果页眉标记超过60px(相当于两行),则将填充设置为,但如果自动高度小于该高度,则将填充设置为...

h1[height>60px] { padding:10px 0px; }
h1[height<60px] { padding:20px 0px; }

我希望这是有道理的。我只是不知道该怎么写。还是有更好的办法?

请参见示例。

http://jsfiddle.net/KcD3v/

非常感谢

推荐答案

您可以尝试这样做:

HTML

<div class="header">
    <h1>This would be 2 lines of text</h1>
    <h1>This is 1 line</h1>
    <h1>This would be 2 lines of text</h1>
    <h1>This is 1 line</h1>
    <h1>This would be 2 lines of text</h1>
    <h1>This is 1 line</h1>
    <h1>This would be 2 lines of text</h1>
    <h1>This is 1 line</h1>
</div>

css

.header {
    display: inline-table; /* IE8+, Chrome, FF3+, Opera7+ */
}

h1 {
    display: table-cell;
    margin:5px;
    padding:5px;
    width:100px;
    height:50px;
    vertical-align: middle;
    text-align:center;
    background:#336699;
    color:#fff;
}

这样可以在不破坏网站语义的情况下使用表格。有关display和表格样式的更多详细信息,请查看MDN。

但是,通常每个页面只有一个<h1>元素用于定义网站的页面标题,然后使用<h*>元素的所有其他组合。

如果你不需要跨浏览器的兼容性(例如,如果你正在开发一些Chrome/Firefox扩展/Webapp),那么即使是新的flexbox也可能是一个有趣的选择。

另一种方法是将代码中的vertical-align更改为<h1>元素的高度,但在这种情况下,您将被限制为一行文本。