使用CSS
将#dates div
对齐到标题的右侧,并垂直在中间,这是最好/最干净的方法。
我尝试了float: right
,但不允许vertical-align
。我想避免使用浮动,所以我使用inline-block
,并使用相对定位。有没有更正确的方法?
我不喜欢我必须把顶部设置为30px,然后不断尝试,直到它居中。
<div id="header">
<a id="logo" href="~/" runat="server">
<img src="Images/Interface/logo.png" alt="logo" />
</a>
<div id="dates">
<div id="hijri-date">2 Ramadhaan, 1435 AH</div>
<div id="gregorian-date">Sunday 29 June 2014</div>
</div>
</div>
#header
{
background-color: white;
padding: 15px;
position: relative;
}
#logo
{
display: inline-block;
vertical-align: middle;
}
#logo img
{
vertical-align: bottom; /* to get rid of text descender space underneath image */
}
#dates
{
display: inline-block;
position: absolute;
right: 30px;
top: 30px;
font-size: 14px;
font-family: 'Open Sans';
color: #696969;
background: url(Images/Interface/date-icon.png) no-repeat;
background-position-y: center;
padding-left: 32px;
}
你可以使用css display:table
:
#header {display:table; width:100%;}
#logo,
#dates {display:table-cell; vertical-align:middle}
例子你可能需要给#dates一个宽度,如果你想让它向右对齐
使用Inline-Blocks
使用你的HTML元素,试试下面的CSS:#header {
background-color: yellow;
padding: 15px;
text-align: justify;
line-height: 0;
}
#logo {
display: inline-block;
vertical-align: middle;
}
#logo img {
vertical-align: bottom;
/* to get rid of text descender space underneath image */
}
#dates {
display: inline-block;
line-height: 1.5;
font-size: 14px;
font-family:'Open Sans';
color: black;
background-image: url(http://placehold.it/100x100);
background-position: center;
padding-left: 32px;
}
#header:after {
content: '';
display: inline-block;
vertical-align: top;
width: 100%;
}
由于您在#header
中有两个子元素,左侧的徽标图像和右侧的文本块,只需使用text-align: justify
强制徽标在左侧,文本在右侧。
要使其工作,您需要在#header
中至少有两行。
要生成第二行,使用伪元素:#header:after
,它将在日期之后放置一个100%宽的空白内联块。width: 100%
强制它开始并填充第二行,vertical-align: top
消除基线以下的额外空白。
要处理高度中的空白,在#header
中设置line-height: 0
,这将允许伪元素的高度崩溃为0。但是,您需要重置#dates
中的line-height: 1.5
以获得清晰的文本。
优点和缺点
使用这种方法,随着页面宽度变小,元素最终将换行为两行。
如果你想保持元素在一行上,你最好使用CSS表格。
参见demo: http://jsfiddle.net/audetwebdesign/3U3w4/
我认为,垂直对齐的最佳方法是使用css:display-table
和css"display-table-cell
属性。如果你想在id="dates"中向右对齐,你应该在这个块中使用css:display-inline-table
。
#header {
background: #fff;
padding: 15px;
background: #ccc;
display: table;
}
#logo {
display: table-cell;
}
#dates {
display: table-cell;
text-align: right;
font-size: 14px;
font-family: 'Open Sans';
color: #696969;
}
看到小提琴
使用display: flex;
属性可以设置项目水平和垂直居中。