使用display对象图像居中:table-cell

时间:2016-03-09 13:27:42

标签: css

我想在容器块中居中对齐并底部对齐<img><img>需要约束到容器维度,因此会在其上设置max-width:100%max-height:100%。另外,我需要将标签与<img>的右上角对齐,这会使事情变得更复杂。

我使用display:inline-blockline-height(下方)的工作版本:

&#13;
&#13;
.block {
  line-height: 236px;
  text-align: center;
  width: 236px;
  height: 236px;
  background: rgba(255, 0, 0, .3);
}
.flex {
  background: rgba(255, 0, 0, .3);
  display: inline-block;
  vertical-align: bottom;
  position: relative;
  line-height: 18px;
}
img {
  display: block;
  max-width: 236px;
  max-height: 236px;
  width: auto;
  height: auto;
}
label {
  position: absolute;
  top: 0;
  right: 0;
}
&#13;
<div class="block">
  <div class="flex">
    <img src="http://i.imgur.com/x7q4E80.png" />
    <label>X</label>
  </div>
</div>
<br>
<!-- 374 × 187 -->
<div class="block">
  <div class="flex">
    <img src="http://i.imgur.com/dBy1WKI.png" />
    <label>X</label>
  </div>
</div>
&#13;
&#13;
&#13;

View on Codepen

但是,这需要重置标签的line-height。是否可以使用其他方法(如display:table-cell)对内容进行居中和底部对齐?

我最接近的尝试如下:

&#13;
&#13;
.block {
  display: table-cell;
  vertical-align: bottom;
  width: 236px;
  height: 236px;
  background: rgba(255, 0, 0, .3);
}
.flex {
  background: rgba(255, 0, 0, .3);
  display: table-cell;
  vertical-align: bottom;
  position: relative;
}
img {
  display: block;
  max-width: 236px;
  max-height: 236px;
  width: auto;
  height: auto;
}
label {
  position: absolute;
  top: 0;
  right: 0;
}
&#13;
<div class="block">
  <div class="flex">
    <img src="http://i.imgur.com/x7q4E80.png" />
    <label>X</label>
  </div>
</div>
<br>
<!-- 374 × 187 -->
<div class="block">
  <div class="flex">
    <img src="http://i.imgur.com/dBy1WKI.png" />
    <label>X</label>
  </div>
</div>
&#13;
&#13;
&#13;

View on Codepen

1 个答案:

答案 0 :(得分:0)

您可以像下面一样简化代码。

.block1 {
  background-color: red;
  width: 100px;
  height: 100px;
  position: relative;
}
.block2 {
  background-color: red;
  width: 100px;
  height: 100px;
  position: relative;
  margin-top: 10px;
}
.block1 a {
  width: 20px;
  height: 20px;
  vertical-align: middle;
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
.block1 a label {
  position: absolute;
  top: 4px;
  right: 0;
  line-height: 0;
}
.block2 a {
  width: 20px;
  height: 20px;
  vertical-align: middle;
  margin: auto;
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
}
.block2 a label {
  position: absolute;
  top: 4px;
  right: 0;
  line-height: 0;
}
<div class="block1">
  <div class="ctr-algn">
    <a href="#">
      <img src=".../images">
      <label>x</label>
    </a>
  </div>
</div>

<div class="block2">
  <div class="ctr-algn">
    <a href="#">
      <img src=".../images">
      <label>x</label>
    </a>
  </div>
</div>

我希望你解决问题。