skip to Main Content

I have img and I want if the image can’t load, the alt appears in the middle of the image and if it’s too big it becomes an ellipsis and it should be on one line

img { 
  width: 150px;
  height: 75px;
  background: #111;
  display:flex;
  align-items:center;
  overflow:hidden;
  text-overflow: ellipsis;
  color:#fff;
  white-space: nowrap;
}
<img src="" alt="Lorem ipsum dolor sit amet">

please no margin , padding or line-height tricks i can’t use any of them because the img height is 100% i can’t know what is the final height

the code for firefox only so it must work in newest firefox version

2

Answers


  1. You just need to add display: inline-block to your image and it will work.

    This won’t center the text though and won’t hide the broken image icon.

    img { 
      width: 150px;
      height: 75px;
      background: #111;
      display:flex;
      align-items:center;
      text-overflow: ellipsis;
      color:#fff;
      white-space: nowrap;
      display: inline-block;
    }
    <img src="" alt="Lorem ipsum dolor sit amet">
    Login or Signup to reply.
  2. Use a pseudo element for this:

    img { 
      width: 150px;
      height: 75px;
      display: block;
      overflow:hidden;
      color:#fff;
      position: relative;
      resize: both; /* resize the image to see the effect */
    }
    img:before {
      content: attr(alt);
      position: absolute;
      /* this will center the element */
      inset: 0;
      height: min-content;
      max-width: min-content;
      margin: auto;
      /**/
      border-image: linear-gradient(#111 0 0) fill 0//100vw; /* a trick that will make sure the color covers all the area outside the element */
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow:hidden;
    }
    <img src="" alt="Lorem ipsum dolor sit amet">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search