Search code examples
htmlcsstooltip

CSS pseudo element tooltip has the same width as the original element


Here i got the code.

body {
	padding: 5px 10px;
	background-color: #E5E2D9FF;
}

abbr {position: relative}

abbr:hover:after {
  content: attr(title);
  position: absolute;
  color: #FFFFFFD7;
  background-color: #0000009C;
  padding: 2px 5px;
  bottom: 0; right: 0;
  transform: translate(100%, 100%);
  border-radius: 0 5px 5px 5px;
}
<h1>CSS Tooltips</h1>
	<h2>Simple tooltip</h2>
	<h3>With 'abbr' tag</h3>
	<p><abbr title="This is a simple tooltip">Lorem</abbr> ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati ea quae iste, voluptates nihil nesciunt laboriosam saepe magnam, odio molestiae architecto! Reprehenderit exercitationem magnam, illo possimus vero ducimus, commodi magni!</p>

I want that the :after pseudo element's width is different from the original element.

Thanks :)


Solution

  • Just set a width to pseudoelement.

        body {
        	padding: 5px 10px;
        	background-color: #E5E2D9FF;
        }
    
        abbr {position: relative}
    
        abbr:hover:after {
          content: attr(title);
          position: absolute;
          color: #FFFFFFD7;
          background-color: #0000009C;
          padding: 2px 5px;
          bottom: 0; right: 0;
          transform: translate(100%, 100%);
          border-radius: 0 5px 5px 5px;
          white-space: nowrap;
        }
    <h1>CSS Tooltips</h1>
    <h2>Simple tooltip</h2>
    <h3>With 'abbr' tag</h3>
    <p><abbr title="This is a simple tooltip">Lorem</abbr> ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati ea quae iste, voluptates nihil nesciunt laboriosam saepe magnam, odio molestiae architecto! Reprehenderit exercitationem magnam, illo possimus vero ducimus, commodi magni!</p>

    Of course, you can set max/min-width, combine with non-width and white-space: no-wrap if you have just short texts with unknown width and want them on one line, etc.