raulbaros raulbaros - 3 months ago 13
CSS Question

Position divs in corners of an image

I am trying to position "BRAND" in the top right corner, and "CATEGORY" in the bottom right corner, of an image.

I am close.

But how do I make it fit exactly inside the image and in the corners top right and bottom right?



.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>




Answer

You can make the container (div.image) a relatively-positioned bounding box, which will allow you to absolutely position the children within its borders:

.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>

Notes:

  1. Establish nearest positioned ancestor for absolute positioning.
  2. Width of container is width of in-flow content
  3. Use absolute positioning with offset properties (top, bottom, left, right) to move child elements within container