【问题标题】:Vertically align item inside floating DIV that is inside LI垂直对齐 LI 内的浮动 DIV 内的项目
【发布时间】:2014-09-29 08:13:04
【问题描述】:

我有一个包含 div 的列表

<ul>
    <li>
        <div class="date">today</div>
        <div class="desc">lorem ipsum</div>
        <div class="action">
            <p>
                <a class="button">X</a>
            </p>
        </div>
    </li>
    <li>....</li>
    <li>....</li>
</ul>

如何在 div.action 中垂直对齐 a.button?

该列表的 CSS 是使用 Susy 生成的,CSS 看起来像这样:

ul {
  list-style: none outside none;
}
li {
  margin-left: 12.766%;
  margin-right: 12.766%;
  margin-bottom: 10px;
  background-color: #eee;
  display: block;
}
li:after {
  clear: both;
  content: "";
  display: table;
}

.date {
  float: left;
  margin-right: 2.12766%;
  width: 10.6383%;
}
.desc {
  float: left;
  margin-right: 2.12766%;
  width: 74.4681%;
}

.action {
  float: right;
  text-align: center;
  margin-right: 0;
  width: 10.6383%;
}

我不知道 LI 的高度,因为“desc”文本可以是任意长度。

这里是 codepen.io 的代码 -> http://codepen.io/anon/pen/CFhos

【问题讨论】:

  • 任何floated 都会自动上升到其包含块的顶部。如果你想让它垂直居中,你必须使用不同的方法来对齐右边的按钮。

标签: html css vertical-alignment susy


【解决方案1】:

Flexbox 几乎可以对齐任何东西——甚至是浮动元素...

只需将以下规则添加到li

display: flex;
align-items: center; /*align vertical */

Updated CODEPEN

【讨论】:

    【解决方案2】:

    您可以像这样设置按钮的样式:

    .button{
        position: relative;
        top: 50%;
        transform: translateY(-50%);
    }
    

    此处的示例:http://jsfiddle.net/4amdxtq8/

    【讨论】:

      【解决方案3】:

      您可以在不浮动的情况下执行此操作:

      ul {
        list-style: none outside none;
      }
      li {
        display: table;
        margin-left: 12.766%;
        margin-right: 12.766%;
        margin-bottom: 10px;
        background-color: #eee;
      }
      p {
        display: table-cell;
        margin: 0;
        padding: 0;
      }
      li:after {
        clear: both;
        content: "";
        display: table;
      }
      
      .date {
        display: table-cell;
        vertical-align: middle;
        margin-right: 2.12766%;
        width: 10.6383%;
      }
      .desc {
        display: table-cell;
        vertical-align: middle;
        margin-right: 2.12766%;
        width: 74.4681%;
      }
      
      .action {
        display: table-cell;
        vertical-align: middle;
        margin-right: 0;
        width: 10.6383%;
      }
      

      http://codepen.io/anon/pen/yxhkA

      【讨论】:

        猜你喜欢
        • 2013-09-03
        • 2014-04-24
        • 2010-11-04
        • 2011-05-31
        • 2014-01-23
        • 2021-05-30
        • 2020-05-18
        • 2016-11-20
        • 1970-01-01
        相关资源
        最近更新 更多