样式 "bottom:0" 也向左对齐

Style "bottom:0" also aligns to left

我已将 bottom:0 设置为 div 以使其在底部对齐。但是,即使我的文本是 text-center,它也是左对齐的。我想知道为什么?

.box {
  width: 100%;
}
.box:before {
  content: "";
  display: block;
  padding-top: 100%;
}
.content {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  padding: 7%;
}
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="col-xs-4">
  <a href="#" class="thumbnail">
    <div class="box">
      <div class="content">
        <div>
          <img src="http://placehold.it/350x150" alt="Title" class="img-responsive center-block">
        </div>
        <div class="caption" style="position:absolute;bottom:0;">
          <p class="text-center">Title</p>
        </div>
      </div>
    </div>
  </a>
</div>

对于绝对 定位的 元素,text-center 将不起作用 元素上作为 absolute 元素从流程中删除

您可以像这样使用 transform 将其居中:

transform: translateX(-50%);
left: 50%;

.box {
  width: 100%;
}
.box:before {
  content: "";
  display: block;
  padding-top: 100%;
}
.content {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  padding: 7%;
}
.caption {
  position: absolute;
  bottom: 0;
  transform: translateX(-50%);
  left: 50%;
}
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="col-xs-4">
  <a href="#" class="thumbnail">
    <div class="box">
      <div class="content">
        <div>
          <img src="http://placehold.it/350x150" alt="Title" class="img-responsive center-block">
        </div>
        <div class="caption">
          <p class="text-center">Title</p>
        </div>
      </div>
    </div>
  </a>
</div>

父元素 div 应将宽度设置为页面宽度的 100%,然后子 p 元素将自行对齐到页面中心。

在您当前的代码段中,div 元素集没有宽度,这就是为什么它采用其子元素内容的宽度。

由于使用 class 内容应用的填充,它仍然会偏离中心一点。

您应该只对图像容器应用此填充 div。

.box {
  width: 100%;
}
.box:before {
  content: "";
  display: block;
  padding-top: 100%;
}
.content {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
.padding7 {
  padding: 7%;
}
.caption {
  position: absolute;
  bottom: 0;
  width: 100%
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="col-xs-4">
  <a href="#" class="thumbnail">
    <div class="box">
      <div class="content">
        <div class="padding7">
          <img src="http://placehold.it/350x150" alt="Title" class="img-responsive center-block">
        </div>
        <div class="caption">
          <p class="text-center">Title</p>
        </div>
      </div>
    </div>
  </a>
</div>