在CSS中居中放置高度未知的图像上的文字

问题描述 投票:0回答:2

我正在寻找一个问题的解决方案,时间长达一个小时,而我在互联网上发现的内容与我所寻找的内容完全不符。我想使用CSS在图像上居中放置文本。图像的高度是根据div的宽度(百分比)自动定义的。

这里是html代码:

<div>
  <img src="image.jpg" id="image"/> 
  <span id="texte"> Texte </span>
</div>

这里是CSS代码(无效):

#div
{
  position: relative;
  margin: 0px;
  padding: 0px;
  width:45%;
  text-align:center;
}

#texte
{
  display: block;
  padding: 0px;
  margin-left:auto;
  margin-right:auto;
  z-index: 2;
}

#image
{
  width:100%;
  height:auto;
  display: block;
  padding: 0px;
  z-index: 1; 
}

感谢您的帮助。

css image text center
2个回答
0
投票

[如果从CSS的div中删除#(因为它是标签,而不是ID),然后将以下属性添加到#text块中:

position: absolute; /* so that the "top" property can be applied */
top: 50%; /* puts the top of the element halfway down what it's relative to, in this case the div */
margin-top: -.6em; /* assuming no wrapping, this slight adjustment makes it so the middle of the text (instead of its top) runs roughly through the middle of the parent */
width: 100%; /* in case you meant horizontal centering instead. this allows the parent's "text-align: center" to be applied */

我认为应该可以满足您的需求。如果文本长于一行,并且您需要精确的垂直居中,我认为您必须使用JavaScript解决方案。这是一个JS Fiddle,其中包含您的CSS和我的编辑内容(尽管现在可能不再需要某些CSS)。


0
投票

尝试一下

* {
  box-sizing: border-box;
  font-family: sans-serif;
}

.container {
   position: relative;
   overflow: hidden;
}

img {
   width: 100%;
   opacity: .8;
} 

.centered-text {
   display: inline-block;
   position: absolute;
   top: 50%;
   left: 50%;
   color: white;
   padding: .7em 1em;
   text-align: center;
   font-size: 1.5em;
   background-color: rgba(0, 0, 0, .4);
   -webkit-transform: translate(-50%, -50%);
   -moz-transform: translate(-50%, -50%);
   -o-transform: translate(-50%, -50%);
   -ms-transform: translate(-50%, -50%);
   transform: translate(-50%, -50%);
}
<div class="container">
  <img src="https://parrot-tutorial.com/images/nature_autumn.jpg">
  <span class="centered-text">Text</span>
</div>

参考: How To Position Text Over an Image

© www.soinside.com 2019 - 2024. All rights reserved.