【问题标题】:Center a combination of text and image within a DIV将 DIV 中的文本和图像组合居中
【发布时间】:2018-04-18 13:42:11
【问题描述】:

我尝试在容器 DIV 中居中(水平和垂直)文本和图像的串联。这是代码:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #myBox {display:block; width:300px; height:100px;
              text-align:center; font-size:20px; line-height:500%;
              background-color:yellow;}
      #myImg {display:block; width:33.33%; height:100%;}
    </style>
  </head>
  <body>
    <div id="myBox">
      My text
      <img id="myImg" src="red100x100.jpg" />
    </div>
  </body>
</html>

文本确实居中,但图像出现在新行中。

试图实现这一点:

但我明白了:

编辑:

这类似于center image next to two lines of text responsively,但后者也处理margin:auto的效果,而本题没有。

【问题讨论】:

标签: html css image centering


【解决方案1】:

1) 将display:inline-block; 用于#myImg

2) 使用vertical-align: middle; 将文本垂直居中。

#myImg {
    display:inline-block;
    vertical-align: middle;
    //Other code...
}

#myBox {
  display:block;
  width:300px;
  height:100px;
  text-align:center;
  font-size:20px;
  background-color:yellow;
}

#myImg {
  display:inline-block;
  width:33.33%;
  height:100%;
  vertical-align: middle;
}
<div id="myBox">
  My text
  <img id="myImg" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQEnn9dYYZlciBKfaHCw17-dUgRPX3nq5_6-kV1ua-LIsId5g43uA" />
</div>

【讨论】:

  • 谢谢。它有效(我忘记了“内联”的事情......)还必须摆脱文本的“行高”以获得更好的垂直对齐。
【解决方案2】:

当图像被渲染为一个块时,它会换行到下一行。您可以将其显示从块更改为内联,然后将另一个属性 - 垂直对齐 - 设置为中间。

#myImg {
    display: inline;
    vertical-align: middle;
    width: 33.33%;
    height: 100%;
}

Codepen - https://codepen.io/sassquad/pen/GOqQxe

【讨论】:

    猜你喜欢
    • 2019-11-01
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2018-07-24
    • 2012-07-30
    相关资源
    最近更新 更多