2017-07-17 128 views
0

我知道这个问题已被问了很多,但我一直没能找到答案中的解决方案。我正在尝试在图片中居中放置文字,但我在垂直对齐方面遇到了一些麻烦。这是我的代码:垂直对齐图像上的文本

<div class="col-sm-12 col-md-12 col-lg-12 main_category_container"> 
    <div class="col-sm-4 col-md-4 col-lg-4"> 
     <div class="wrap"> 
      <h3 class="sub_category_title"><a href="some link">Centered text</a></h3> 
      <a href="some link"><img src="some image"></a> 
     </div> 
    </div> 
</div> 

.wrap { 
height:auto; 
margin: auto; 
text-align:center; 
position:relative; 
} 

h3.sub_category_title { 
vertical-align: middle; 
} 

眼下文本图像上方水平居中,但我无法弄清楚如何垂直对齐图像的中间。

提前致谢!

+0

文字和图片都有'href'。如果您将标题垂直对齐,您是否认为这可能会导致混淆哪个元素用于哪个链接? – Nimish

+0

他们都指向相同的链接。我已经尝试过一些类似的东西,只是一个没有链接的h3,但我认为你不能直接点击文本有点混乱。有没有更好的方法来做到这一点?我很新:) – Mewb

回答

0

通常,如果您尝试将一个元素与另一个元素重叠,则最终会使用position: absoluteposition: relative - 否则,内容自然会排列在区块流中。

你可以尝试这样的事:

.image-wrapper { 
 
    position: relative; 
 
    text-align: center; 
 
    
 
    width: 300px; /* change or remove as needed */ 
 
    margin: auto; 
 
} 
 

 
.image-link { display: block; } 
 

 
.image-text { 
 
    position: absolute; 
 
    top: 50%; 
 
    left: 0; 
 
    right: 0; 
 
    margin: auto; 
 
    
 
    /* The rest of this is just for this demo, 
 
    you can change it for your situation. */ 
 
    
 
    font-weight: bold; 
 
    color: white; 
 
    font-family: sans-serif; 
 
    background: rgba(0, 0, 0, 0.5); 
 
}
<div class="image-wrapper"> 
 
    <a class="image-link" href="#"> 
 
    <img class="image" src="http://loremflickr.com/300/200" alt="kitten!"> 
 
    <h3 class="image-text">A Centered Label</h3> 
 
    </a> 
 
</div>

+0

完美的工作:)谢谢杰克! – Mewb