如何使用锚点和图像垂直居中浮动 div

How to vertical center floated div with anchor and image

我想将我的图像置于浮动的 div 中。我试过 vertical-align:middle; 但没有成功。我想那是因为它是浮动的。

我创建了一个关于我的问题的 jfiddle:https://jsfiddle.net/au0h6u0g/

请看一下是否居中

  .container
{
  float:right;
  text-align: center;
  width:100%;
}

.container img {
  display: inline-block;
}

您可以将 display:table; 用于 .top,将 display:table-cell; 用于 vertical-align:middle; 用于 .container

.top
{
  width:100%;
  height: 150px;
  background-color:blue;
  display:table;
  direction:rtl;
}

.container
{
  display:table-cell;
  vertical-align:middle;
}
<div class="top">
  <div class="container">
    <a href="#">
      <img src="http://lorempixel.com/400/200/" alt="Smiley face" height="50"     width="140">
    </a>
  </div>
</div>

你应该看看 Flexbox

.top,添加声明:

display: flex;
flex-direction: row;
align-items: center;

.container 中添加:

flex: auto 1 0;

最后,将 float: right 声明移至 image 而不是容器。

查看更新后的 Fiddle

https://jsfiddle.net/au0h6u0g/5/

您可以使用绝对定位并根据元素大小进行偏移转换。

<div class="top">
  <div class="container">
      <img src="http://lorempixel.com/400/200/" alt="Smiley face" height="50"     width="140">
  </div>
</div>

.top
{
  height: 150px;
  background-color:blue;
}

.container
{
  position: relative;
  height: 150px;
}

.container img{
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);

}

您可以在 imgline-height 上使用 vertical-align,例如:

.top {
  height: 150px;
  background-color: blue;
}

.container {
  float: right;
  line-height: 150px;
}

img {
  vertical-align: middle;
}
<div class="top">
  <div class="container">
    <a href="#">
      <img src="http://lorempixel.com/400/200/" alt="Smiley face" height="50" width="140">
    </a>
  </div>
</div>

https://jsfiddle.net/au0h6u0g/4/

从答案的数量可以看出,有许多 种方法可以做到这一点。这是另一个要求您将 img 绝对定位在每个轴上的 0px 处,然后使用 margin:0 将其居中:

.top {
  height: 150px;
  background-color:blue;
  position:relative;
}

.container img {
  float:right;/* < this is redundant but you said that you must have it.*/
  position:absolute;
  top:0; right:0; bottom:0; left:0;
  margin:auto;
}
<div class="top">
  <div class="container">
    <a href="#">
      <img src="http://lorempixel.com/400/200/" alt="Smiley face" height="50" width="140">
    </a>
  </div>
</div>