需要水平和垂直居中对齐图像和文本

时间:2018-08-10 00:28:31

标签: html css

我可以将它们垂直和水平居中对齐,但是我既需要它们作为一个单元来水平居中,又要使文本在图像旁边垂直居中。

这是我所拥有的:

<div style="text-align: center; height: 50px; position: relative; border: 1px solid black;">
    <img src="img/image.jpg"><span style="margin-left: 150px; position: absolute; top: 50%; left: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%);">SOMETEXT<span>
</div>

如果我的文字上没有“ margin-left”,那么它们会彼此重叠,但是在空白处它们会偏离中心。

我已经浏览了数十个关于类似问题的Stackoverflow答案,但是许多答案已经过时了,不再能使用/支持了,或者这不是我所需要的。

TIA!

3 个答案:

答案 0 :(得分:2)

您也可以通过简单的CSS技巧来做到这一点

div{
  display:flex;
  flex-wrap:wrap;
  justify-content:center;
  align-items:center;
}

答案 1 :(得分:1)

喜欢吗?

<div style="text-align: center; height: 50px; line-height: 50px; position: relative; border: 1px solid black;">
  <img src="img/image.jpg" style="vertical-align: middle;">
  <span>SOMETEXT<span>
</div>

答案 2 :(得分:1)

.element{ 
  justify-content:center;
  align-items:center; 
}
相关问题