简体   繁体   中英

Can you set css min-width relative to another element?

I have a nav menu of links and sub menu. I want the submenu min width to be that of the link. Is this possible in CSS? I'm using LESS if that helps at all.

<ul>
   <li>
    <a href="">Item FooBarBaz</a>
    <ul class="submenu">
        <li><a>sub1</a></li>
        <li><a>sub2</a></li>
        <li><a>sub3</a></li>
    </ul>
   </li>
   <li>
       <a href="">Item FooBarBazZipBamBop</a>
       <ul class="submenu">
        <li><a>sub1</a></li>
        <li><a>sub2</a></li>
        <li><a>sub3</a></li>
       </ul>
   </li>
</ul>

I want each ul.submenu to have the min-width of the previous sibling anchor. Obviously this would be a potentially different value for each submenu. Is this possible in CSS? Or is jquery, javascript a better solution here?

Sure. Here is an example: http://jsfiddle.net/SeKT9/

ul
{
    margin:0;
    padding:0;
    list-style:none;
}



body > ul > li 
{
    float: left;
    position: relative;
}

ul > li  a
{
    display: block;
    margin: 5px;
}

ul > li:hover > ul
{
    display: block;
}

ul > li > ul
{
    position: absolute;
    min-width: 100%;
    background-color: green;
    display: none;
} 

ul > li > ul > li
{
    display: block;
}

Maybe just adding an inline-block div around each submenu is quicker/easier? I'm always hesitant to add many lines of code for a small simple effect.

<ul>
   <li>
    <div style='display:inline-block;'>
        <a href="">Item FooBarBaz</a>
        <ul class="submenu">
            <li><a>sub1</a></li>
            <li><a>sub2</a></li>
            <li><a>sub3</a></li>
        </ul>
    </div>
   </li>
   <li>
    <div style='display:inline-block;'>
       <a href="">Item FooBarBazZipBamBop</a>
       <ul class="submenu">
        <li><a>sub1</a></li>
        <li><a>sub2</a></li>
        <li><a>sub3</a></li>
       </ul>
    </div>
   </li>
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM