Home > Mobile >  How to set width of span tag to be the same as its content?
How to set width of span tag to be the same as its content?

Time:01-13

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 ></i>
   My Text
 </span>

CodePudding user response:

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 >
  <i ></i>
   My Text
 </span>
 
 <span >
  <i ></i>
   My Text
 </span>

CodePudding user response:

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

CodePudding user response:

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 >
  <span>
  <i ></i>
   My Text
   </span>
 </span>

  • Related