position:absolute和vertical-align:middle

时间:2016-11-09 11:23:07

标签: css css-position vertical-alignment

如何在我的示例中设置第三列以使vertical-align: middle作为所有其他行?我意识到问题出在position: absolute,但我无法弄清楚如何解决问题。

https://jsfiddle.net/pr1v6Lhd/1/

即使使用top定位也不适用于.data

我的HTML:

<table border="1">
  <tbody>
    <tr>
      <td>ADMIN</td>
      <td>222387</td>
      <td width='50' style='position:relative'>
        <div class='data'>59853.94</div>
        <div class="bar-chart-bar">
          <div class="bar" style='width:50%; background-color:#B8E4F5'></div>
        </div>
      </td>
      <td width="50">0</td>
      <td>59853.94</td>
      <td>4189.82</td>
      <td>7</td>
    </tr>
  </tbody>
</table>

我的CSS:

.bar-chart-bar {
  background-color: #e8e8e8;
  display: block;
  position: relative;
  width: 100%;
  height: 20px;
}

.bar {
  float: left;
  height: 100%;
}

.data {
  position: absolute;
  z-index: 1;
  display: block;
  top: 10;
}

.table > tbody > tr > td {
  vertical-align: middle;
}

table {
  font-size: 12px;
}

3 个答案:

答案 0 :(得分:2)

是的,您需要从.data中移除position: absolute,并绝对定位.bar-chart-bar并相应地设置z-index:

.bar-chart-bar {
  background-color: #e8e8e8;
  display: block;
  position: absolute;
  width: 100%;
  height: 20px;
  top: 0;
  left: 0;
  z-index: -1;
}

https://jsfiddle.net/jamesking/pr1v6Lhd/2/

答案 1 :(得分:1)

display:table添加到班级data

&#13;
&#13;
.bar-chart-bar {
  background-color: #e8e8e8;
  display: block;
  position: relative;
  width: 100%;
  height: 20px;
}

.bar {
  float: left;
  height: 100%;
}

.data {
  position: absolute;
  z-index: 1;
  display:table;
}

.table > tbody > tr > td {
  vertical-align: middle;
}

table {
  font-size: 12px;
}
&#13;
<table border="1">
  <tbody>
    <tr>
      <td>ADMIN</td>
      <td>222387</td>
      <td width='50' style='position:relative'>
        <div class='data'>59853.94</div>
        <div class="bar-chart-bar">
          <div class="bar" style='width:50%; background-color:#B8E4F5'></div>
        </div>
      </td>
      <td width="50">0</td>
      <td>59853.94</td>
      <td>4189.82</td>
      <td>7</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

删除位置并使数据div成为bar div的子项。

.bar-chart-bar {
  background-color: #e8e8e8;
  display: block;
  width: 100%;
}

.bar {
  float: left;
  height: 100%;
}

.data {
  z-index: 1;
}

.table > tbody > tr > td {
  vertical-align: middle;
}

table {
  font-size: 12px;
}
<table border="1">
  <tbody>
    <tr>
      <td>ADMIN</td>
      <td>222387</td>
      <td width='50' style='position:relative'>
        <div class="bar-chart-bar">
            <div class="bar" style='width:50%; background-color:#B8E4F5'>
                <div class='data'>59853.94</div>
            </div>
        </div>
      </td>
      <td width="50">0</td>
      <td>59853.94</td>
      <td>4189.82</td>
      <td>7</td>
    </tr>
  </tbody>
</table>