垂直对齐图像 [英] Vertical-align image

查看:114
本文介绍了垂直对齐图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div,其中包含一个图像和一个p标签(见下文)。我想要在div的中间垂直对齐图像,这取决于段落的行数。垂直对齐不起作用。我现在使用JavaScript来计算多少添加到margin-top,但宁愿使用CSS。任何想法?

I have a div that contains an image and a p tag (seen below). I want to align the image in the middle of the div vertically depending on how many lines the paragraph is. Vertical-align doesn't work. I am using JavaScript right now to figure out how much to add to margin-top, but would rather use CSS. Any ideas?

<div>
    <img>
    <p>Multi-line</p>
</div>


推荐答案

p 元素的高度属性到图像的高度,例如:

Try setting the line-height attribute of the p element to the height of the image, eg:

div p {
  line-height: 18px;
}

编辑:意识到我误解了问题,错过了 p 将是多行的事实。尝试的一个选项是删除 img 元素,并将其设置为<$ c $的 background-image c> p ,而 background-position 则为 left,center 。像:

Just realised I misread the question and missed the fact the p would be multi-line. One option to try is removing the img element altogether and setting it as the background-image of the p instead, with a background-position of left, center. Something like:

div p {
  background: transparent url(path/to/img) no-repeat left center;
  padding-left:30px; /* Set based on width of image */
}

这篇关于垂直对齐图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆