2

I am trying to create a simple thumbnail gallery with each image has a text below it. However, since the images I am dealing with have various sizes, I decided to crop and center each image in the gallery. I actually did this following the instructions given here:

https://jonathannicol.com/blog/2014/06/16/centre-crop-thumbnails-with-css/

However, texts of the images appear on the image. I could not find a way to move the text to the below. I tried adding padding to bottom but padding-bottom is not working. I suspect it is due to height: auto line. Somehow this setting preventing me to adjust padding in the vertical direction.

My html:

<div class="gallery">
    <img src="https://placehold.it/900x500" alt="">
    <div class="desc">My Text</div>
</div>
<div class="gallery">
    <img src="https://placehold.it/500x900" class="portrait" alt="">
    <div class="desc">My long long text</div>
</div>

Styling:

.gallery {
    position: relative;
    width: 200px;
    height: 200px;
    overflow: hidden;
    margin-top: 5vh;
    margin-right: 0.5vh;
    border: 1px solid #ccc;
    float: left;
}

.gallery img {
    position: absolute;
    left: 50%;
    top: 50%;
    height: 100%;
    width: auto;
    -webkit-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

.gallery img.portrait {
    width: 100%;
    height: auto;
}

.desc {
    display: block;
    position: absolute;
    top: 85%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
}

jssfiddle:

https://jsfiddle.net/8ue603on/

Thank you!

cagri
  • 71
  • 8

2 Answers2

1

I think a better solution for you will be use object-fit for image https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

.gallery img {
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    width: 100%;
    object-fit: cover;
}

https://jsfiddle.net/csscoder/wymLkq16/3/

0
  1. Set a max-height to the images, it will look cleaner than setting max-width.

  2. You should review all major aspects of CSS because then you would know about object-fit which you can experiment with at MDN.

  3. If you have varying lengths of text you can't choose the number of characters short of messing with JavaScript though you won't need to. Put the text inside of a span element and set it to display: block so that you only have an img and span inside of the parent and the text appears below the image. You can get an ellipsis from overflowing text.

  4. Never put text directly inside of a div - they are block level elements. Yes, you can technically get away with it though when you get to very high levels of skill you will find that have strict policies of how you work with code will greatly benefit and expedite your projects.

John
  • 1
  • 13
  • 98
  • 177