html - 垂直居中 float 图像

标签 html css

我的 UI 中有几个按钮,它们必须让图像 float 在文本旁边,而且效果很好。但是,我在将该图像与文本垂直对齐时遇到问题。

我已经尝试了多种方法以及 vertical-align: center;,尝试使用绝对定位,我什至尝试了一些转换技术,但都失败了。

现在这些按钮的内容来自用户,所以它是动态的,否则我会尝试用行高做一些事情,然后收工。

任何帮助都会很棒!

我的 html 看起来像这样。

<div class='btn-primary col-md-4'>
    <img  src='https://developers.google.com/web/fundamentals/imgs/placeholder--small.png'/ >
        <span class='imgInfo'>This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. This is info. </span>
        <p class='clearfix'></p>
</div>

CSS 看起来像这样。

img{
    vertical-align: middle;
    float:left;
    width:50%;
}

.imgInfo{
    margin-left: 0px;
    overflow:auto;
    display:block;
    float:right;
    width:50%;
    padding-left:1em
}

和一个 jsFiddle 与 http://jsfiddle.net/52VtD/7356/ 搭配使用

最佳答案

Demo

CSS

img{
    float:left;
    width:50%;;
    position: absolute;
    top:0;
    bottom:0;
    margin: auto;
}

(引用:Smashing Magazine)

说明

在研究了规范和文档之后,这就是绝对居中的工作原理:

  1. normal content flow 15, margin: auto; 顶部和底部等于'0'。
    W3.org 16:如果‘margin-top’或‘margin-bottom’为‘auto’,则它们的使用值为0。
  2. position: absolute; 将 block 从典型的内容流中分离出来,呈现其余内容,就好像该 block 不存在一样。
    Developer.mozilla.org 17: …绝对定位的元素从流中取出,因此不占用空间
  3. 设置顶部:0;左:0;底部:0; right: 0; 为浏览器提供一个新的 block 边界框。此时,该 block 将填充其偏移父级中的所有可用空间,即主体或 position: relative; 容器。 Developer.mozilla.org 1918:对于绝对定位的元素,top、right、bottom 和 left 属性指定距元素包含 block 边缘的偏移量(元素相对于什么定位)。
  4. 为 block 指定宽度高度可防止 block 占用所有可用空间并强制浏览器计算margin: auto基于新的边界框。 Developer.mozilla.org 1918:[绝对定位] 元素的边距随后位于这些偏移量内。
  5. 由于 block 是绝对定位的,因此在正常流之外,浏览器为 margin-topmargin-bottom 赋予相等的值,使元素在边界中居中早点设置。
    W3.org 20:如果三个[top, bottom, height]都不是'auto':如果'margin-top'和'margin-bottom'都是'auto',在两个边距相等的额外约束下求解方程值。又名:垂直居中 block

根据规范,绝对居中似乎是 margin: auto; 的预期用途,因此应该适用于所有符合标准的浏览器。

TL;DR:绝对定位的元素不会在正常流中呈现,因此 margin: auto;top 设置的边界内垂直居中: 0;左:0;底部:0;右:0;

关于html - 垂直居中 float 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25145280/

相关文章:

html - 悬停时在光标旁边显示图像

html - 当我调整浏览器大小时如何阻止我的网页 div 元素四处移动

html - 图标在 IE7 中不显示

javascript - 如何在不添加浏览器的情况下打印 html

css - 我试图让两个 cels 大小相同,但左边的保持更大

javascript - 为什么我的页面在隐藏一些元素后会刷新?

javascript - 更改其他 div 中的高度后,我的固定边栏 float 在页脚上方

jquery - 如何让所有图像全屏?

html - JQUERY 突出显示悬停

javascript - 删除水平滚动条