I have a dropdown menu, and I’m trying to get the submenus to be the same width as the top level page.
My HTML is structured like something this (This is for a wordpress theme, so I have very little control over the document structure):
<ul class="menu">
<li class="menu-item-has-children menu-item">
<a>Top Level Page 1</a>
<ul class="submenu">
<li class="menu-item-has-children menu-item">Sub Page 1</li>
<li>Sub Page 2</li>
<li>Sub Page 3</li>
</ul>
</li>
<li class="menu-item-has-children menu-item">
<a>Top Level Page 2 which has a different width</a>
<ul class="submenu">
<li>Sub Page 4</li>
<li>Sub Page 5</li>
<li>Sub Page 6</li>
</ul>
</li>
</ul>
I first turned to CSS:
ul.menu li ul {
width: 100%;
}
… but that makes it the width of the ul.menu for some reason. I also tried putting the “width: 100%” in other places, but no such luck.
I decided to turn to jquery, inspired by this post. I tried this initially:
$('ul.menu li ul').width($(ul.menu li).width());
…but it just sets all the submenus to the width of the first li, ignoring parenting relationships.
I’ve tried each of the following to select just the parent (or the sibling a, in case that’s what’s determining the width) of that particular ul, but none of them seem to work:
$('ul.menu li ul').width($(this).parent('li').width());
$('ul.menu li ul').width($(this).parent().width());
$('ul.menu li ul').width($(this).parent('li').children('a').width());
$('ul.menu li ul').width($(this).siblings('a').width());
Can you not use $this in this context? If so, what would be a better way to accomplish what I’m trying to do?
you’re overthinking this:
Assuming you haven’t defined any child elements of
.menu
as relative or absolute this will align the submenu to the left hand side of.menu
and obviously the widths are defined as the same.Edits:
Use google chrome inspector to see what css rules are being applied to the elements but a couple of examples of what can be done with css.
Natural flow (submenu is a block item and will fill parents width
https://jsfiddle.net/cpe0pqhk/
or defined rules
https://jsfiddle.net/z011176r/1/
Now for the jQuery version:
Before explaining this you should note:
jQuery needs to be included on the frontend – this is a lot of code for changing css values, this takes time for the user to download and use
WP expects the word
jQuery
as a call rather than$
which will generate a error (check your console)jsfiddle:
https://jsfiddle.net/71dyqjvr/1/