通过css将页眉标签与固定高度垂直对齐 [英] Vertically Align a Header Tag with Fixed Height through CSS

查看:0
本文介绍了通过css将页眉标签与固定高度垂直对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个固定宽度的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;
}

也许...就像一个基于自动高度确定两个不同填充属性的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>元素的高度,但在这种情况下,您将被限制为一行文本。

这篇关于通过css将页眉标签与固定高度垂直对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆