簡體   English   中英

如何在文本中間垂直放置文本?

[英]How can I place text in the middle of an image vertically?

我想將博客條目標題放在垂直對齊中間的條目縮略圖上。

圖像大小會隨着窗口大小的變化而變化,並且博客條目標題可能會超過兩行,具體取決於每個博客條目。

我發現這個網站成功地將文本垂直對齊到圖像的中間。

在下面的頁面上,您會看到三張帶有標題的圖像。

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的新手,最近我一直在努力學習CSS。

謝謝!

注意

  • 如前所述,圖像大小會隨着窗口大小的變化而變化。
  • 條目標題可能超過兩行。 這取決於一篇文章。
  • 它也需要與IE8兼容。
  • 我不想將圖像視為div的背景。我想在代碼中使用img標簽。

保留您的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)
}

我添加了一個半透明的背景,以便可以看到效果,但是當然可以隨意調整。 在Codepen上查看

這是在現代瀏覽器中執行此操作的一種簡單方法: 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM