February 4, 2013
Inline-block, Inline, Block
Question by Zettam
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?
Answer by Starx
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");
}