简体   繁体   English

如何在块元素中垂直居中放置图像和文本? [CSS]

[英]How to vertically center image and text in a block element? [CSS]

帮我

I am trying to accomplish this with CSS. 我正在尝试使用CSS完成此任务。 Here is my markup: 这是我的标记:

<h2>
  <img src="A.gif" alt="A" width="30" height="30" />
  <img src="B.gif" alt="B" width="30" height="30" />
  18 pt; vertically centered;
</h2>
  • A and B are 30x30 pixel images. AB是30x30像素的图像。
  • Small red lines are 5 pixels paddings/margins (whichever works) 小红线为5像素的填充/边距(以有效为准)
  • As a result of the images' height and vertical padding, the outermost container has a height of 40px (30+5+5). 由于图像的高度和垂直填充,最外面的容器的高度为40px(30 + 5 + 5)。
  • The width of the outermost container is 100%. 最外层容器的宽度为100%。

Note: There is no chance the 18pt text will overflow the width of the container. 注意: 18pt文本将不会溢出容器的宽度。 Assume it will always be one line. 假设它将始终是一行。

Note: If more markup would help get the desired view, the markup can be modified. 注意:如果更多标记将有助于获得所需的视图,则可以修改标记。

How can this be accomplished? 如何做到这一点?

If I'm not mistaken, you can use the vertical-align: text-bottom property on an img to achieve this kind of result. 如果我没记错的话,可以在img上使用vertical-align: text-bottom属性来实现这种结果。

Here's a little test: http://www.w3schools.com/Css/tryit.asp?filename=trycss_vertical-align 这是一个小测试: http : //www.w3schools.com/Css/tryit.asp?filename=trycss_vertical-align

You can try removing the styles there and replacing them with 您可以尝试删除那里的样式并将其替换为
img { vertical-align: text-bottom; }
and the text should be aligned to the desired centre of the page element. 并且文本应与页面元素的所需中心对齐。

You can set the line-height to 40px, that should cause the text to be vertically centred if it is only one line. 您可以将line-height设置为40px,如果只有一行,则应该使文本垂直居中。

h2 {
    line-height: 40px;
}
h2 img {
    padding: 5px;
    vertical-align: middle;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM