垂直对齐图像
我有一个包含图像和 ap 标签的 div(如下所示)。我想根据段落的行数将图像垂直对齐在 div 中间。垂直对齐不起作用。我现在正在使用 JavaScript 来计算要添加到 margin-top 的量,但更愿意使用 CSS。有什么想法吗?
<div>
<img>
<p>Multi-line</p>
</div>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是纯 CSS,垂直对齐图像,如果图像比包含框更高(或更宽),还会缩小图像的大小。因此,框和图像都可以是任意大小,而不会破坏垂直对齐。此外,您可能需要向
标记添加左边距,以防止它们被图像隐藏。
CSS
This is pure CSS, vertically aligns the image, and also resizes the image down if it's taller (or wider) than the containing box. Ergo, the box and image can both be any size without breaking the vertical alignment. Also, you may want to add a left margin to the
<p>
tags to keep them from being hidden by the image.CSS
尝试将
p
元素的line-height
属性设置为图像的高度,例如:编辑: 刚刚意识到我误读了问题并且错过了
p
是多行的事实。可以尝试的一种选择是完全删除img
元素,并将其设置为p
的background-image
,并使用background -
。像这样的东西:左、中
的位置Try setting the
line-height
attribute of thep
element to the height of the image, eg:Edit: Just realised I misread the question and missed the fact the
p
would be multi-line. One option to try is removing theimg
element altogether and setting it as thebackground-image
of thep
instead, with abackground-position
ofleft, center
. Something like:给图像显示:block,float:left和vertical-align:middle。或者,为其指定与包含元素相同的行高。
Give the image display: block, float: left and vertical-align: middle. Or, give it a line height equal to that of the containing element.
CSS 垂直对齐属性仅适用于表格单元格和内联元素。由于段落标记默认指定块元素,因此它不执行任何操作。为了使您的文本按照您所描述的方式对齐,您必须将 div 分成两个容器或使用表格。这是一个很好的页面,可以帮助您更好地理解:了解vertical-align
the CSS vertical-align attributes only works on table cells and inline elements. Since the paragraph tag specifies a block element by default, it does nothing. In order for your text to be aligned as you describe, you either have to separate your div into two containers or use a table. Here's a good page to help you understand a little bit better: Understanding vertical-align
这是一个两栏的工作吗? (图像在左边,文本在右边)
如果是这样,你当然可以将每个元素粘贴在自己的 div 中......
认为这会做你想要的事情
Is it kind of a two column job? (image to the left, text to the right)
If so, you could surely just stick each element in its own div...
Think that would do what you're after
也许 Jak psát web 上的解决方案会有所帮助。
Maybe the solution at Jak psát web will help.
添加
Add