Biker John
Biker John

Reputation: 2711

<ul> fit parent <li> width

I would like my nested <ul id='child'> to fit parent <il id='parent'> width.

HTML:

<ul>
<li id='parent'>
  <a href='#' id='setter'>$variable</a>
  <ul id='child'>
    <li>one</li>
    <li>two</li>
  </ul>   
</li>
</ul>

CSS:

#setter {padding:0 15px; display:inline-block} /*as menu item*/
#child {...?}

The problem is that link is setting the <li> width since the link text is changeable variable. With other words, <li> width cannot be fixed.

Upvotes: 2

Views: 5970

Answers (3)

gilly3
gilly3

Reputation: 91497

You can float the <li>:

#parent
{
    float: left;
}

http://jsfiddle.net/G3TBn/4/

But then, if the content in #child grows wider than #setter, the width of the <li> will grow as well:

http://jsfiddle.net/G3TBn/5/

In that case, you could then position #child absolutely:

#parent
{
    float: left;
    position: relative;
}
#child
{
    position: absolute;
    left: 0;
    right: 0;
}

http://jsfiddle.net/G3TBn/6/

But, then that can cause layout flow issues (which may or may not be an issue):

http://jsfiddle.net/G3TBn/7/

You can set a fixed width at runtime (as opposed to design time) with JavaScript. Measure the inline element whose width you want to use, and set that as the fixed width of the parent element.

document.getElementById("parent").style.width = 
    document.getElementById("setter").offsetWidth + "px";

http://jsfiddle.net/G3TBn/2/

Upvotes: 4

ralph.m
ralph.m

Reputation: 14345

All you need is

#child {margin: 0; padding: 0; }

and maybe width: 100% if you've set a different width elsewhere.

Also, it's <li> ("List Item"), not <il>. :-)

EDIT: If this is a drop down list, you need to wrap the <a> around the sub ` anyway. Here's a better way to go:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">

<style media="all">

ul {list-style: none; margin: 0; padding: 0;}
#setter {background: red; display: block;}
#child {background: blue;}

</style>

</head>
<body>

<ul>
    <li id='parent'>
          <a href='#' id='setter'>$variable
          <ul id='child'>
                <li>one</li>
                <li>two</li>
          </ul>
          </a>   
    </li>
</ul>

</body>
</html>

Upvotes: 2

BobbyZ
BobbyZ

Reputation: 336

I would do so:

#setter {
    position:relative;
    display:inline-block;
    background:yellow;
    padding:0 15px;
}
#child {
    position:absolute;
    background:red;
    width:inherit;
}

might have to adjust padding. but I hope you get the idea.

demonstration

Upvotes: 1

Related Questions