Search code examples
htmlcssparent

Parent Element Bounding Box Relative to Child Element


Ok I've been wanting to ask another question here for some time. I hope this is simple enough and not a repeat...

So I have a list item list with some anchor tags nested inside of them...

<ul class="news">
<li><a href="#">This Link is Longer</a></li>
<li><a href="#">My Links</a></li>
</ul>

like those.

As you can see the first anchor tag's text is longer than the anchor tag below, in that there are more characters present.

I have a background-color on my list items however I would like the background-color/bounding box for each list item to be only as WIDE as the anchor tag within it, it being a list item...(disregard margin and padding)

I have my unordered list area set with a max-width of 40% as it is a piece of a float that is nested inside of a parent div...

ul.news {
    max-width: 40%;
    float: right;
}

ul.news li {
    text-align: right;
    margin: 0px 0px 10px 0px;
    background-color: rgba(57,14,99,1.0);
    padding: 7px;
}

IN SHORT

The background box is setting to the length of the biggest anchor tag. In this example, my link "My Links", has a purple box around it that is as large or as long as the link above it, "This Link is Longer". I will most likely kick myself, but how would I, using CSS, set my li width (I'm assuming width) relative to it's anchor child's size... "My Links" should have a purple box only as big as "My Links" extends (plus 7px padding on each side,of course).

THANK YOU for your helllppp


Solution

  • Make the list items float too

    ul.news li {
        float: right;
    }
    

    Example fiddle