Search code examples
htmlcsstextcenteringmasonry

Centering a paragraph in an inline-block column


I got a masonry style grid like this:

  <div class="masonry">
      <div class="brick">
         <p>Img Title</p>
         <img src="img.jpg">
      </div>
      <div class="brick"> 
       ....
      </div>
  </div>

With this css:

.masonry {
  transition: all .5s ease-in-out;
  column-gap: 00px;
  column-fill: initial;
  box-sizing: content-box;
}

.masonry .brick {
  text-align: center;
  margin-bottom: 0px;
  display: inline-block;
  vertical-align: top;
}

.masonry .brick p{
    color: black;
    position: absolute;
    transition: all .5s ease-in-out;
}

.masonry .brick img {
  max-width: 100%;
  vertical-align: middle;
  transition: all .5s ease-in-out;
  backface-visibility: hidden;
}

How would I center the p tag (vertical and horizontal) in the Masonry layout with css?

Once I change the positioning to something like left=50% it goes to half of the wohle Masonry grid, not the one Masonry brick for some reason. An text-align: center doesn't seem to work at all.

The idea of course being: If you hover over one image it shows the title of the image in the middle.


Solution

  • Use the below updated CSS

    .masonry {
      transition: all .5s ease-in-out;
      column-gap: 00px;
      column-fill: initial;
      box-sizing: content-box;
    }
    
    .masonry .brick {
      text-align: center;
      margin-bottom: 0px;
      display: inline-block;
      vertical-align: top;
      position:relative;
    }
    
    .masonry .brick p{
        color: black;
        position: absolute;
        transition: all .5s ease-in-out;
        left:50%;
        margin:0;
        top:50%;
        transform:translate(-50%,-50%)
    }
    
    .masonry .brick img {
      max-width: 100%;
      vertical-align: middle;
      transition: all .5s ease-in-out;
      backface-visibility: hidden;
    }
    

    You can use position:absolute with left:50% and top:50% to centre the element and you can translate it back half its width and height by using transform:translate(-50%, -50%). To consider the .brick element as the parent for the absolute p element, You have to add position:relative to it.