AlexFoxGill AlexFoxGill - 2 months ago 6
HTML Question

How can I use the exact width of wrapped text rather than that of the full container?

I have some text which is constrained to a particular width, so it wraps. I want to display a border around the wrapped text. When I add a border, it wraps the text plus the unused space around it. Is there a way to apply the border to just the text? Here's an illustration of what I mean: I have drawn a red line where I want the right-hand edge of the element to be:

enter image description here

HTML:



<div>
Supercalifragilistic expialidocious
</div>


CSS:



div {
max-width: 200px;
display: inline-block;
border: 1px solid black;
}


JSFiddle

Answer

Could work. Combining attr() and pseudo.

.outer {
  width: 200px;
  background-color: #ccc;  
  border: 1px solid black;
  display: inline-block;
}
.inner {
  position:relative;
  display: inline;
}
.inner:before {
  content: attr(data-text);
  color: transparent;
  position: absolute;
  left:0;top:0;
  border: 1px solid red;
}
<div class="outer">
  <div class="inner" data-text="Supercalifragilistic expialidocious">Supercalifragilistic expialidocious</div>
</div>

Comments