如何将文本垂直放置在图像中间?

时间:2014-08-23 02:26:28

标签: html css css3

我想在与中间垂直对齐的条目缩略图上放置博客条目标题。

图像大小随窗口大小的变化而变化,博客条目标题可能会超过两行,具体取决于每个博客条目。

我发现这个网站成功地将文本垂直对齐到图像的中间位置。

在下面的页面上,您会看到三个带标题的图片。

https://www.hyperisland.com/community

我阅读了上面网页的代码并尝试了下面的代码,但它没有按照我的预期运行。

这是我到目前为止的代码。

http://codepen.io/anon/pen/kFwAH

HTML

<html lang="ja">
      <head>
      </head>
  <body>

    <div class="articleTitle">
    <h1 class="title"><span>Article title. Artile title. Article Title.Article title.</span></h1>
    <img src="http://placeimg.com/500/500/any" alt="">
    </div>

    </body>
</html>

CSS

.articleTitle {

background: #eee;
position: relative;
}

img {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
z-index: 1;
max-width:100%;
}

h1 {
line-height: 1;
z-index: 2;
position: relative;
height: 100%;
text-align: center;
vertical-align: middle;
}

h1:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
}
h1 span {
display: inline-block;
vertical-align: middle;
}

有人可以帮帮我吗?

我是CSS新手,我最近一直在努力学习。

谢谢!

注意

  • 正如我前面提到的,图像大小会随着窗口大小的变化而变化。
  • 条目标题可能超过两行。这取决于一篇文章。
  • 它也需要与IE8兼容。
  • 我不想将图像视为div的背景。我想在代码中使用img标记。

2 个答案:

答案 0 :(得分:2)

保留您的HTML并通过以下方式更改当前的CSS:

.articleTitle {


position: relative;
  width:400px; height:400px;
}

img {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
z-index: -1;
max-width:100%;

}

h1 {
line-height: 1;
z-index: 2;
position: relative;
text-align: center;
position: relative; transform: translateY(-50%); -webkit-transform:translateY(-50%); top:50%; background:rgba(255,255,255,0.5)
}

我添加了半透明背景,因此您可以看到效果,但当然您可以随意调整。 See it at Codepen

答案 1 :(得分:0)

这是在现代浏览器中执行此操作的简便方法:http://codepen.io/pageaffairs/pen/qCpse

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>

.articleTitle {
    display: table;
    position: relative;
    width: 50%; /* adjust to suit, or leave out altogether if you want it to default to the width of the image */
}

.articleTitle {
    display: table;
    position: relative;
}

h1 {
    margin: 0; 
    text-align: center;
}

span {
    position: absolute; 
    top: 50%; 
    left: 0; 
    right: 0; 
    display: inline-block;
    -webkit-transform:translate(0, -50%);
    -moz-transform:translate(0, -50%);
    -ms-transform:translate(0, -50%);
    -o-transform:translate(0, -50%);
    transform:translate(0, -50%);
}

img {
    display: block; 
    width: 100%;
}
</style>
</head>
<body>

<div class="articleTitle">
    <h1 class="title">
        <span>Article title. Artile title. Article Title.Article title.</span>
        <img src="http://placeimg.com/500/500/any" alt="">
    </h1>
</div>

</body>
</html>
相关问题