Julian
Julian

Reputation: 1831

How to make resizable li elements with CSS only

Scenario: I have an unordered list < ul > of width (lets say 200px) with four < li > elements that are sized equally. Therefore each should be 50px. When I add a 5th < li > element each width should re-size to 40px. If I change the width of the < ul > to 500px with 5 < li > elements, each < li > element should be 100px.

Is this possible with only CSS? If yes, how is it implemented?

Currently, I have a solution that meets the above requirements but it includes jQuery to re-size the < li > elements based on mathematical calculations.

Thanks for the attention.

Upvotes: 0

Views: 1204

Answers (4)

David Thomas
David Thomas

Reputation: 253318

Until such a time as browsers implement the calc(), min() and max() functions this isn't possible outside of scripting (either server-, or client-, side) or using a table.

Currently, and surprisingly (perhaps only to me), neither Firefox, Webkit or Opera support calc() function, not even with the various flavours of vendor prefix.

That said, one day something like the following might work (but not today, sadly):

ul {
  counter-reset: numListItems;
  width: 60%;
}

ul li {
  counter-increment: numListItems;
  width: calc(100%/numListItems);
}

But, obviously, for that to work browsers would need to implement some form, and understanding, of variables within the scope of calc(), which doesn't appear to be necessarily on the road-map (I'm not sure that the counter() is, or is intended to be, interoperable with the calc()).

Upvotes: 0

skajfes
skajfes

Reputation: 8265

Aparently you can fake tables like here, but I am not sure if this works in all browsers(edit: it works on winxp ie8, chrome 7, firefox).

<div id="menu">
    <ul>
        <li>
            <a href="...">...</a>
        </li>
        <!-- other list items -->
    </ul>
</div>

#menu {
    display: table;
}

ul {
    display: table-row;
}

li {
    display: table-cell;
}

Also example on fiddle.net here

Upvotes: 5

Moses
Moses

Reputation: 9173

Using CSS expressions it is possible, but CSS Expressions come with a very heavy performance penalty. JavaScript (and jQuery for that matter) is the appropriate tool to use to create the effect you want.

CSS should only be used for styling, HTML should only be used for structure, and JavaScript should be used whenever you want to create dynamic content.

Upvotes: 0

JohnB
JohnB

Reputation: 18982

Your question doesn't completely make sense to me. If you leave the widths off, the list will be as wide as it needs to be. But here's a crack at your question:

<style type="text/css"> 
ul
{
  width:500px;
}
li
{
  width:100px;
}
</style>

<ul>
  <li>1. one</li>
  <li>2. two</li>
  <li>3. three</li>
  <li>4. four</li>
  <li>5. five</li>
</ul>

Upvotes: 0

Related Questions