首页 > 解决方案 > 试图垂直居中一些跨度

问题描述

这是我的代码:

<div style="text-align: center">
<span style="display: inline-block; font-size: 38px; float: left; cursor: pointer; color: #ccc">❮&lt;/span>
<span style="margin-top: 12px; background: #ccc; border: 1px solid #ccc; border-radius: 50%; height: 13px; width: 13px; cursor: pointer; display: inline-block"></span>
<span style="border: 1px solid #ccc; border-radius: 50%; height: 13px; width: 13px; cursor: pointer; display: inline-block"></span>
<span style="border: 1px solid #ccc; border-radius: 50%; height: 13px; width: 13px; cursor: pointer; display: inline-block"></span>
<span style="display: inline-block; font-size: 38px; float: right; cursor: pointer; color: #ccc">❯&lt;/span>
</div>

这是在 JSFiddle 上:https ://jsfiddle.net/nwvxaofc/

第一个和最后一个跨度左右浮动,而中间的三个跨度水平居中。我希望它们也垂直居中,而且我并不立即明白如何做到这一点。

设置margin-top: 12px似乎没有做任何事情。

如果我设置position: absolute最外面的 div 然后将三个中间跨度包裹在一个<div>with中position: relativetop: 50%那么浮动就会变得混乱。

标签: htmlcss

解决方案


抛弃所有的浮动display:inline-block并使用 flexbox

div {
  display: flex;
  align-items: center;
}

span:first-of-type {
  margin-right: auto;
}

span:last-of-type {
  margin-left: auto;
}
<div style="text-align: center">
  <span style="font-size: 38px; cursor: pointer; color: #ccc">❮&lt;/span>
  <span style=" background: #ccc; border: 1px solid #ccc; border-radius: 50%; height: 13px; width: 13px; cursor: pointer;"></span>
  <span style="border: 1px solid #ccc; border-radius: 50%; height: 13px; width: 13px; cursor: pointer;"></span>
  <span style="border: 1px solid #ccc; border-radius: 50%; height: 13px; width: 13px; cursor: pointer;"></span>
  <span style=" font-size: 38px; cursor: pointer; color: #ccc">❯&lt;/span>
</div>


推荐阅读