CSS 如何垂直对齐div中的标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16356428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to vertical align tag in a div
提问by user850010
I have this HTML code:
我有这个 HTML 代码:
<div class="news_item">
<div class="featured_leftpart">
<img src="" width="48" height="48" />
</div>
<div class="featured_rightpart">
<div class="news_content">
<h2 class="entry-title"><a href="" >TEXT </a></h2>
</div>
</div>
</div>
and using this CSS:
并使用此 CSS:
.news_item
{
width:300px;
position:relative;
padding:10px;
height:100px;
margin:10px;
border:1px solid #e8e8e8;
}
div.featured_leftpart
{
position:relative;
float:left;
width:64px;
height:100%;
}
div.featured_leftpart img{
position:absolute;
background-color:#ff00ff;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}
div.featured_rightpart
{
background-color:#ff0000;
float:left;
width:180px;
padding-left:10px;
height:100%;
}
.news_content
{
background-color:#00ff00;
position:relative;
}
.news_content h2
{
vertical-align:middle;
}
What I'm trying to do is to vertical align h2 tag. This tag will contain a post title, so sometimes it will be single line, sometimes multiline.
Also that <div class="news_content">
is just my attempt to make it work. If there is a solution without this div
, I can easily remove it.
我想要做的是垂直对齐 h2 标签。这个标签将包含一个帖子标题,所以有时是单行,有时是多行。这<div class="news_content">
也只是我试图让它发挥作用的尝试。如果没有这个解决方案div
,我可以轻松地将其删除。
Here is jsFiddlelink to the code above.
这是上面代码的jsFiddle链接。
回答by Passerby
Extending from comment:
从评论扩展:
No need to add an extra .news_content
, just tell browser how high is a line and vertical-align
will work:
无需添加额外的.news_content
,只需告诉浏览器一条线有多高即可vertical-align
:
<div class="featured_rightpart">
<h2 class="entry-title"><a href="" >TEXT </a></h2>
</div>
div.featured_rightpart
{
line-height:100px; /* calculated from .news_item */
}
.featured_rightpart h2
{
vertical-align:middle;
margin-top:0px; /* need this to clear the default margin */
margin-bottom:0px;
}
Beware, though, that this solution only works if there's only one line in title.
但请注意,此解决方案仅适用于标题中只有一行的情况。
Edit:
编辑:
In case multiline is not avoidable, the wrapper seems not avoidable too:
如果多行无法避免,包装器似乎也无法避免:
<div class="featured_rightpart">
<div class="title_wrapper">
<h2 class="entry-title"><a href="" >TEXT<br />multi<br />line </a></h2>
</div>
</div>
div.title_wrapper {
display:inline-block;
vertical-align:middle;
line-height:1.25em; /* can adjust to look nice */
}