cssbackground

How to avoid background being too large on tagcloud with line break


I´m having a tag cloud in a sidebar. Each tag has a background color. When the tag is longer, the text wraps to the next line, but the background is always filling the whole width of the container. How can I make the background smaller, so it ends with the text?

Expected result:

enter image description here

.tagcloud {
  width      : 130px;
  background : #ddd;
  height     : 300px;
  }
.tagcloud a {
  display         : inherit;
  float           : left;
  margin          : 0 5px 5px 0;
  padding         : 6px 10px;
  border-radius   : 3px;
  color           : #fff;
  background      : #282828;
  font-size       : 12px !important;
  line-height     : 1;
  transition      : all .2s;
  text-decoration : none;
  }
<div class="tagcloud">
  <a href="#">foo</a>
  <a href="#">short stuff</a>
  <a href="#">My superlong Superwords</a>
  <a href="#">my short text</a>
</div>
I did search online but could not find a solution


Solution

  • If JS is allowed, you can put the texts into mark elements - this will allow you to find the maximum width of the (possibly wrapped) text.

    Then make the background to the anchor elements the width of this (plus padding).

    <style>
      .tagcloud {
        width: 130px;
        background: #ddd;
        height: 300px;
      }
    
      .tagcloud a {
        display: inherit;
        float: left;
        margin: 0 5px 5px 0;
        padding: 6px 10px;
        border-radius: 3px;
        color: #fff;
        /*background      : #282828;*/
        font-size: 12px !important;
        line-height: 1;
        transition: all .2s;
        text-decoration: none;
        background-repeat: no-repeat;
        background-image: linear-gradient(#282828, #282828);
      }
    
      mark {
        background: transparent;
        color: inherit;
      }
    </style>
    <div class="tagcloud">
      <a href="#"><mark>foo</mark></a>
      <a href="#"><mark>short stuff</mark></a>
      <a href="#"><mark>My superlong Superwords</mark></a>
      <a href="#"><mark>my short text</mark></a>
    </div>
    <script>
      document.querySelectorAll('.tagcloud > a').forEach(a => {
        const s = a.querySelector('mark').getBoundingClientRect();
        a.style.backgroundSize = (s.width + 20) + 'px 100%';
      });
    </script>