-1

I NEED to use display: flex in order to style this icon and text that are within a span tag. As you can see the width is way too long, I just want the width to be just as long as the width of image and text, that's it.

NOTE: If text is longer I always want the width of span to adjust so it's always the same as image and text combine. Can someone point me in the right direction, please? Here's my code:

   span {
 display: flex;
 align-items: center;
 background: #ddd;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<span>
  <i class="fa fa-arrow-right"></i>
   My Text
 </span>
Devmix
  • 1,599
  • 5
  • 36
  • 73

3 Answers3

1

The display: flex property is what is causing the element to behave like a block element. So you can either use flex-inline or just set the width of the block element to max-content.

.option1 {
  display: flex-inline;
  align-items: center;
  background: #ddd;
}

.option2 {
  display: flex;
  align-items: center;
  background: #ddd;
  width: max-content;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<span class="option1">
  <i class="fa fa-arrow-right"></i>
   My Text
 </span>
 
 <span class="option2">
  <i class="fa fa-arrow-right"></i>
   My Text
 </span>
jme11
  • 17,134
  • 2
  • 38
  • 48
  • You can do either option. Either set the `width` or use `flex-inline`. If you need support for older browsers, you can set the width using any length property you like (px, rem, em, ch, etc.). If you need support for IE, well, you're probably out of luck since it doesn't support flex either. :-( – jme11 Jan 12 '23 at 21:28
1

you can simply add width : fit-content; to your span.

-1

If you need to support older browsers you could try this approach which takes a bit more effort.

.test {
  display: flex;
}

.test span {
  position: relative;
}

.test span:before {
  content: "";
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  background: #ddd;
  height: 100%;
  width: 100%;
  z-index: -1;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<span class="test">
  <span>
  <i class="fa fa-arrow-right"></i>
   My Text
   </span>
 </span>
mrp
  • 689
  • 1
  • 8
  • 17