1

I've been searching about CSS lately, trying to teach myself the tricks. One another issue I've encountered is directly related to the display: attribute.

I've been trying to get the width of the background element for my "menu buttons" as wide as the text they contain. The buttons are simply <div> elements.

When I use display:block; all of their width appear as wide as the longest item, and when I set it to display:inline; or display:inline-block they simply appear on the same line, just like how an inline element works.

Now, what I'm wondering is, how can I make them appear like a list, but still make the background color only as long as the text it contains?

2 Answers 2

2

Use a markup structure like this

<ul id="menu">
<!-- By the use of UL you can have the menu displayed as list -->
    <li><a href="#">Home</a></li>
    ...
</ul>

And apply the background CSS on the #menu li a

#menu li a {
    /* a (anchor tag) is an inline tag, so the background 
    will span up to its content only */

    background: url("../src/to/img.jpg");
}
Sign up to request clarification or add additional context in comments.

2 Comments

Oh that looks like a good solution, but, is there any way witout needing to change the hierarchy? I can switch to 'ul' and 'li' items but creating a whole new system with href content will be a lot of work..
@Zettam, Since you want to apply the background to the content, you need an inline element or similar to make it behave like it.
1

If you want keep the format, have them wrap around the text and have a line for each item the inline-block or inline isn't an option. You'll have to use floats.

You can force each element on a seperate line by floating your items "float:left;" and forcing the floated elements on other lines with clear:both;

.item{
float:left;
clear:both;
}

Here's an example: http://jsfiddle.net/Bn9Qx/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.