将div放在图像的角落中

时间:2016-08-24 22:39:51

标签: html css html5 css3

我正在尝试定位"品牌"在右上角," CATEGORY"在图像的右下角。

我很接近。

但是,如何使其完全适合图像内部以及右上角和右上角的角落?



.category {
  font-size: 10px;
  font-weight: 700;
  font-family: 'Montserrat', sans-serif;
  font-style: bold;
  text-align: center;
  color: #777;
  margin-left: 15px;
  outline: 1px solid #fff;
  padding: 2px 20px 2px 8px;
  background-color: yellow;
  opacity: 0.9;
  z-index: 3;
  display: block;
  float: right;
  position: relative;
  opacity: 0.7;
  bottom: 0;
  left: 0;
  min-height: 0;
}
.brand {
  font-size: 10px;
  font-weight: 700;
  font-family: 'Montserrat', sans-serif;
  font-style: bold;
  text-align: center;
  color: #777;
  margin-left: 15px;
  outline: 1px solid #fff;
  padding: 2px 20px 2px 8px;
  background-color: #fff;
  opacity: 0.9;
  z-index: 3;
  display: block;
  float: right;
  position: relative;
  opacity: 0.7;
  top: 0px;
  right: 0px;
  min-height: 0;
}
.image {
  max-width: 100%;
  margin: 0;
  display: block;
  padding: 0px;
}

<div class="image">
  <a href="#" target="_blank">
    <img alt="img" src="http://lorempixel.com/400/400">
  </a>

  <div class="brand">
    Brand</div>

  <div class="category">
    Category
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您可以将容器(div.image)设置为相对定位的边界框,这样您就可以将子项绝对定位在其边界内:

.image {
  position: relative;           /* 1 */
  display: inline-block;        /* 2 */  
}
.brand {
  position: absolute;           /* 3 */
  top: 0;
  right: 0;
  color: white;
  font-weight: bold;
}
.category {
  position: absolute;           /* 3 */
  bottom: 0;
  right: 0;
  color: white;
  font-weight: bold;
}
<div class="image">
  <a href="#" target="_blank">
    <img alt="img" src="http://lorempixel.com/400/400">
  </a>
  <div class="brand">Brand</div>
  <div class="category">Category</div>
</div>

注意:

  1. Establish nearest positioned ancestor for absolute positioning.
  2. 容器宽度是流入内容的宽度
  3. 使用具有偏移属性的绝对定位(topbottomleftright)来移动容器中的子元素