文本居中于图像内部

时间:2017-08-14 11:13:49

标签: html css image sass

<div>
  <img style="vertical-align:middle" src="https://placehold.it/60x60">
  <span style="">Product</span>
</div>

我需要这样,它也必须是响应性的。你能告诉我怎么做吗?

enter image description here

6 个答案:

答案 0 :(得分:1)

所以这个问题之前已被多次提出过,这是我过去回答过的重复片段。希望您可以将自己的代码用于显示的示例:)

&#13;
&#13;
div.counter {
    position: relative;
    display: inline-block;
}
div.counter span {
    position: absolute;    
    text-align: center;
    height: 100%;
    width: 100%;
}
div.counter span:before {
   display: inline-block;
   vertical-align: middle;
   height: 100%;
   content: '';
}
&#13;
<div class="counter">
    <span>Product</span>
    <img src="http://placehold.it/60x60"/>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

下面是代码将为您做什么。

<!DOCTYPE html>
<html>
<head>
<style>
.center {
    margin: auto;
    width: 60%;
    border: 3px solid #73AD21;
    padding: 10px;
}
</style>
</head>
<body>

<h2>Center Align Elements</h2>
<p>To horizontally center a block element (like div), use margin: auto;</p>

<div class="center">
  <p><b>Note: </b>Using margin:auto will not work in IE8, unless a !DOCTYPE is declared.</p>
</div>

</body>
</html>

只需将 background-image 属性放在div样式中。

答案 2 :(得分:1)

一种方法是将文字设为position: absolute;。另一种是将图像作为背景。

#sample-1 img {
  vertical-align: middle;
}

#sample-1 {
  position: relative;
  display: inline-block;
}

#sample-1 span {
  position: absolute;
  left: 5px;
  top: 20px;
}

#sample-2 {
  background-image: url('https://placehold.it/60x60');
  width: 60px;
  height: 60px;
  text-align: center;
}

#sample-2 span {
  line-height: 60px;
}
<div id="sample-1">
  <img src="https://placehold.it/60x60">
  <span>Product</span>
</div>

<div id="sample-2">
  <span>Product 2</span>
</div>

答案 3 :(得分:0)

尝试this

<div class="demo">
 <img style="vertical-align:middle" src="https://placehold.it/200x200">
 <span style="">Product</span>
</div>

CSS

.demo {
 width:200px;
 position:relative;
}
.demo span{
 position:absolute;
 left: 0;
 right: 0;
 top: 50%;
 text-align: center;
 margin: -9px auto 0;
}

答案 4 :(得分:0)

使用下面的代码我已经设置了行高等于div高度,它也是响应

&#13;
&#13;
#imgContainer{
		background: url(https://placehold.it/60x60);
		background-position: center;
		background-repeat: no-repeat;
		background-size: cover;
		height: 100%;
		width: 100%;
		text-align: center;
	}
	#imgDesc{
		top: 50%;
        position: relative;
	}
&#13;
<div id="imgContainer">
	  <span id="imgDesc">Works.</span>
	</div>
&#13;
&#13;
&#13;

答案 5 :(得分:-1)

.image {
    position:relative;
}

.image img {
  width:300px;
}
.text {
    left: 0;
    position:absolute;
    text-align:center;
    top: 100px;
    width: 300px
}
<div class="image">
    <img src="https://placehold.it/60x60"/>
    <div class="text">
      Text
    </div>
</div>