Search code examples
htmlcssborderbackground-color

background and border wrap text according to longest line - CSS


I am trying to wrap a paragraph and UL with 4 lines in border and give it black background.

I want the border and background to wrap all the text according to the length of the longest line, I was able to do it for one line at a time but it means that there is no background color between the lines while I want the background and the border to wrap all the text together.

can't figure out how to do it.

This is the HTML code I have

<p><span class="commentBorder">
    some text about the next lines:
</span></p>
<ul>
    <li><span class="typesBorder1">first line text.</span></li>
    <li><span class="typesBorder2">second line text.</span></li>
    <li><span class="typesBorder3">third line text.</span></li>
    <li><span class="typesBorder4">fourth line text.</span></li>
</ul>

this is the CSS code I have:

.commentBorder{
    background-color: rgba(0,0,0,0.5);
    border: 1px solid black;
}
.typesBorder1{
    background-color: rgba(0,0,0,0.5);
    border: 1px solid black;
}
.typesBorder2{
    background-color: rgba(0,0,0,0.5);
    border: 1px solid black;
}
.typesBorder3{
    background-color: rgba(0,0,0,0.5);
    border: 1px solid black;
}
.typesBorder4{
    background-color: rgba(0,0,0,0.5);
    border: 1px solid black;
}


Solution

  • You mean something like this?:

    .parent {
        width: fit-content;
        background-color: rgba(0,0,0,0.5);
        border: 1px solid black;
        margin: 0 auto;
    }
    <div class="parent">
    <p><span class="commentBorder">
        some text about the next lines:
    </span></p>
    <ul>
        <li><span class="typesBorder1">first line text.</span></li>
        <li><span class="typesBorder2">second line text.</span></li>
        <li><span class="typesBorder3">third line text.</span></li>
        <li><span class="typesBorder4">fourth line text.</span></li>
    </ul>
    </div>

    Unfortunately, there is no "clean" way to achieve this, unless you add a parent layer that wraps the ensemble.

    Note that I have added width: fit-content to it so that it adjusts to the widest element.