将div中的H1垂直居中以匹配相邻的div

时间:2014-01-15 12:57:28

标签: html css

我试图将div中的h1标题居中显示在包含小图像的相邻div旁边。不幸的是,无论我尝试什么,h1始终保持在div的顶部。

这是html:

<header>
    <div class="page-header">
        <div class="page-title-icon"></div>
        <div class="page-title"><h1>The heading</h1></div>
    </div>
</header>

这是css

.page-header {
  border:0;
  margin: 20px 0;
  padding-bottom: 0;
}

.page-title-icon {
  display: inline-block;
  height:60px;
  width:60px;
  background:url(./icons-rollovers.png);
  background-position:-46px -829px;
}

.page-title {
  display: inline-block;
  color:#c82e3d;
  text-transform: uppercase;
  height:60px;
}

.page-title h1 {
    line-height: 60px;
 }

有什么想法吗?

4 个答案:

答案 0 :(得分:2)

废弃多余的div会不会更好,并做这样的事情:

<强> HTML:

<header>
    <h1>The heading</h1>
</header>

<强> CSS

header h1 {
    margin:20px 0;
    padding-bottom:0px;
    text-transform: uppercase;
    color:#c82e3d;
    line-height: 60px;
    padding-left:60px;
    position:relative;
 }

header h1:before{
    content: " ";
    position:absolute;
    left:0px;
    width:60px;
    height:60px; 
    background:url(./icons-rollovers.png) left center no-repeat;
    background-position:-46px -829px;   
}

Slightly simplified JSFiddle

答案 1 :(得分:1)

使用原始标记的解决方案显示在以下CSS中:

.page-header {
  border:0;
  margin: 20px 0;
  padding-bottom: 0;
    border: 1px dotted blue;
}

.page-title-icon {
  display: inline-block;
  height:60px;
  width:60px;
  background:url(http://placekitten.com/100/100);
  background-position:-46px -829px;
    vertical-align: top;
    border: 1px dashed blue;
}

.page-title {
  display: inline-block;
  color:#c82e3d;
  text-transform: uppercase;
  height:60px;
    border: 1px dashed blue;
}

.page-title h1 {
    line-height: 60px;
    border: 1px dotted blue;
    margin: 0;
 }

vertical-align: top应用于.page-title-icon元素,以消除由于线路引导而产生的额外空白区域。

margin: 0应用于h1,因为h1的默认边距会产生额外的空白区域,导致垂直对齐。

否则,你基本上得到了答案。

请参阅演示:http://jsfiddle.net/audetwebdesign/LmWGm/

注意:我添加了边框来说明各种元素的边缘,这些可以删除。

答案 2 :(得分:0)

看看他的http://jsfiddle.net/naVS2/2/ 希望它有所帮助 - 诀窍是给行高度50%的包装div。

.page-header {
  border:0;
  margin: 20px 0;
  padding-bottom: 0;
}

.page-title-icon {
  float:left;
  height:60px;
  width:60px;
  background:url(http://jsfiddle.net/img/logo.png);
    border:solid red;
}

.page-title {
     color: #C82E3D;
    float: left;
    height: 60px;
    text-transform: uppercase;}

.page-title h1 {
    line-height: 30px;
 }

答案 3 :(得分:0)

这不是你所追求的最终解决方案,但应该让你开始。尝试做这样的事情。

HTML:

<div class="page-header">
    <div class="page-title-icon">
        <h1>The heading</h1>
    </div>
</div>

CSS:

.page-header {
    display:inline-block;
}
.page-header .page-title-icon {
    display:inline;
    padding:0 0 0 60px;
    background:url(./icons-rollovers.png);
    background-position:-46px -829px;
}