Search code examples
htmlcsshyperlinkpaddinglistitem

How can I remove all padding between my link <a> and the list item it lives in <li>? or... click on <li> opens the link inside of it?


My code:

<ul class='sub-menu'>
  <li><a href='something'>something</a></li>
  <li><a href='else'>else</a></li>
  <li><a href='another'>another</a></li>
</ul>

I can click on the outside of any of the list items(li), and the link won't open (like there is padding between the link itself and the list item it lives in). I want to be able to click on any part of the list item and for the link inside of it to open.

I've been fiddling with inline CSS to try and force the behavior I want but still no luck. Help?


Solution

  • Create a pseudo-element on the anchors, which covers their list items, including the bullets:

    .sub-menu li {
      position: relative;  /* to contain the absolute-positioned pseudo-element */
    }
    
    .sub-menu a:before {
      content: '';         /* required for most pseudo-elements */
      position: absolute;  /* absolutely positioned */
      top: 0;              /* ... at top of its list item */
      left: -50px;         /* ... to the left of its list item, including the bullet */
      right: 0;            /* to its list item's right */
      height: 100%;        /* the height of its list item */
    }
    

    Snippet:

    .sub-menu li {
      position: relative;  /* to contain the absolute-positioned pseudo-element */
    }
    
    .sub-menu a:before {
      content: '';         /* required for most pseudo-elements */
      position: absolute;  /* absolutely positioned */
      top: 0;              /* ... at top of its list item */
      left: -50px;         /* ... to the left of its list item, including the bullet */
      right: 0;            /* to its list item's right */
      height: 100%;        /* the height of its list item */
    }
    <ul class='sub-menu'>
      <li><a href='something'>something</a></li>
      <li><a href='else'>else</a></li>
      <li><a href='another'>another</a></li>
    </ul>