How to stop my background colour extending past my text (CSS)

Viewed 23

I am struggling to prevent my background colour from extending past the text within it. I would ideally like the spacing on the right to match the spacing on the left but, as shown in this screenshot below, the right side will not shorten to match the left:

enter image description here

The code I am using for this is:

 <td>{user.workforce_roles.filter((wf_role) => wf_role.role.visible).map((wf_role) => {
    return <span key={wf_role.id} className="d-block">{wf_role.role.friendly_name}</span>;
  })}</td>

and styling:

.d-block {
  background-color: map-get($theme-colors, 'gapped');
  border-radius: px-to-rem(4px);
  margin-bottom: px-to-rem(6px);
  margin-right: px-to-rem(6px);
  padding: px-to-rem(2px) px-to-rem(8px);
  padding-right: px-to-rem(8px);
  position: relative;
}

It seems as though the width of the background is matching the longest text result but I'm not sure how to make it specific to each text case. Any help is greatly appreciated!

1 Answers

I believe it's because your span elements are display: block elements. Switch it to display: inline-block.

display: block example:

span {
  display: block;
  border-radius: 5px;
  background-color: gray;
  padding: 5px;
  margin: 20px;
}
<span>Text Text</span>
<span>Text Text Text Text Text Text Text Text</span>

display: inline-block example:

span {
  display: inline-block;
  border-radius: 5px;
  background-color: gray;
  padding: 5px;
  margin: 10px;
}
<span>Text Text</span><br>
<span>Text Text Text Text Text Text Text Text</span>

Related