skip to Main Content

I have a row of four images displayed next to each other, and I want to show text beneath each image when hovered over. The text should remain hidden until hover and should not affect the content’s width. However, when I position the text absolutely, I struggle to center it properly under each image. Any idea how to solve it?

Snippet of my current structure:

<div class"items">
 <div class="item-single">
  <a href="">
   <img src="">
  </a>
  <p>Long text under image</p>
 </div>
</div>

If I set item-single to position:absolute;, I cannot center text properly under each respective image. Setting item-single to position:relative; makes the text fit inside the div, which can cause unwanted multi-line text.

3

Answers


  1. Chosen as BEST ANSWER

    I added the following to the p element, and it seems to do the job. The p element is absolute, while its parent is relative.

        text-wrap: nowrap;
        left: 50%;
        transform: translate(-50%,0);


  2. You need to understand how the position relative and absolute work together.

    By adding margin: auto; along with position absolute should solve your problem.

    This should help.

    .item-single {
      position: relative;
      
      height: 201px;
      width: 201px;
      border: 1px solid #333;
    }
    
    .item-single a:hover ~ p {
      display: block;
    }
    
    .item-single p {
      text-align: center;
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      padding: 2px;
      
      display: none;
    }
    <div class"items">
    
      <div class="item-single">
        <a href="https://placehold.co/200">
         <img src="https://placehold.co/200" />
        </a>
        <p>Long text under image</p>
      </div>
      
      
    </div>
    Login or Signup to reply.
  3. .dropdown {
      position: relative;
      display: inline-block;
    }
    .dropdown-content {
      display: none;
      position: absolute;
      left: 50%;
      transform: translate(0, -50%);
      z-index: 1;
    }
    .dropdown:hover .dropdown-content {display: flex;}
    <div class="dropdown" >
    <a href="">
      <img src="img_nature_wide.jpg" alt="Nature">
      </a>
      <p class="dropdown-content">Long text under image</p>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search