具有多个内容(img 和换行文本)的 div 的垂直居中
我想显示 div 中列出的小框。每个盒子都有固定的宽度和高度,里面有一个图像和一些文本(图像就像图标,它们具有相同的宽度和高度)。与旁边的文本相比,图标相当大,所以我想将它们垂直居中放置。
现在,我的代码如下所示:
<div class="hbutton">
<div class="hwrap">
<img style="vertical-align:middle; float:left;" height="40" src="icon.png" width="40" />
<span>Some very long text displayed in the box.</span>
</div>
</div>
为了使 hwrap div 居中,我使用了这个技巧。没有其他 div,没有其他设置。
居中本身工作正常,但如果我在 img 附近放置长文本,并且它不适合,则文本开始换行,但第二行从图像下方开始,而不是在第一行下方。
我想看到什么:
我看到的是:
我也尝试过将文本放入 div 并更改周围的属性,但我就是不能'让它发挥作用。有什么想法吗?
I would like to display little boxes listed in a div. Every box has a fixed width and height, and inside they have an img and some text (the images are like icons, they're the same width and height). The icons are quite large compared to the text next to them, so I would like to position them vertically centered.
Now, my code looks like this:
<div class="hbutton">
<div class="hwrap">
<img style="vertical-align:middle; float:left;" height="40" src="icon.png" width="40" />
<span>Some very long text displayed in the box.</span>
</div>
</div>
For centering the hwrap div, I used this trick. No other divs, no others settings.
The centering itself works fine, but if I put a long text near the img, and it doesn't fit, the text starts wrapping, but the second line start under the image, instead of under the first line.
What I WANT to see:
What I see instead:
I've also tried putting the text into a div and changing the attributes around, but I just can't make it work. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不一定简单,但以下内容似乎可以实现您的目标(请记住,我将文本元素从
span
更改为p
,出于个人/语义原因):html:
css:
JS Fiddle 演示。
This isn't necessarily easy, but the following seems to achieve your aims (bear in mind that I changed the text-element from
span
top
, for personal/semantic reasons):html:
css:
JS Fiddle demo.
编辑:
使用相同的标记,我将添加以下 CSS 属性:
这样,跨度本身永远不会有理由超出那么远...您可以添加您需要的任何其他定位它是为了展示你的品味——但你应该明白这个想法。
编辑:我刚刚注意到这种方法与 David Thomas 的方法几乎相同。 +1。
Edit:
Using the same mark up, I would add the following CSS properties:
This way, the span itself never has a reason to be that far over... you can add whatever other positioning you need for it to display to your taste--but you should get the idea.
Edit: I just noticed that this approach is almost identical to David Thomas' approach. +1.
我已经在此链接下找到了问题的完美解决方案。
它可以正确地对单行和多行文本进行垂直居中,无需任何解决方法,也无需指数级数量的 div!
I've found the perfect soution for the problem under this link.
It does the vertical centering with both single and multiline text properly without any workaround, and without the exponential number of divs!