Home > Back-end >  How to make an anchor element cover all space inside a list item?
How to make an anchor element cover all space inside a list item?

Time:11-05

I am trying to make an anchor element cover all vertical space inside a list item. Because when I hover on a list item element, the href attribute of the anchor doesn't trigger. It triggers just if I hover on the text of the anchor element, doesn't trigger when above or below the anchor element. There is vertical space above and below of anchor element. I set margins to 0 but no effect. The schema is like this:

How the CSS should be?

li {
  background: pink;
}

a {
  background: #ddd;
}
    <ul>
      <li>
        <a href="">Text</a>
      </li>
    </ul>

SCSS snippet:

ul {
        display: block;
        text-align: center;
        cursor: pointer;

        // a:not(.button) {
        //   display: inline-flex;
        // }

        li {
          justify-content: center;
          align-items: center;
          margin: 0;
          padding: 0;
          // padding: $header-nav--padding-v__mobile * 0.5 0px;
          // border-radius: 10px;

          &:hover,
          &:active {
            background-color: #ffffff13;
          }

          a {
            width: 100% !important;
            height: 100% !important;
            display: block !important;
          }

          ul { 
            text-decoration: none;
            display: block;
            position: relative;
            list-style: none;
            padding: 0%;
            margin: 0%;

            li:hover {
              background-color: color-bg(button-primary-hover);
            }
          }
        }
      }

CodePudding user response:

You can use the width attribute to make it fill all the space of the parent element. You will also need to set display to block so it knows to fill up the whole parent.

ul {
  background: magenta;
}

li {
  background: lime;
}

.link {
  background: cyan;
  width: 100%;
  display: block;
}
<ul>
  <li>
    <a href="https://example.org" >Lorem ipsum dolor sit</a>
  </li>
  <li>
    <a href="https://stackoverflow.com" >second element</a>
  </li>
</ul>

To cover the vertical size, use the height and padding attributes:

I also added a different link colour on hover so the user knows what link they're hovering on.

ul {
  background: magenta;
}

li {
  background: lime;
}

.link {
  background: cyan;
  width: 100%;
  height: 100%;
  display: block;
  padding: 2px;
}

.link:hover {
  color: black;
}
<ul>
  <li>
    <a href="https://example.org" >Lorem ipsum dolor sit</a>
  </li>
  <li>
    <a href="https://stackoverflow.com" >second element</a>
  </li>
</ul>

  • Related