How do I make the whole area of a list item in my navigation bar, clickable as a link?

会有一股神秘感。 提交于 2019-11-26 19:48:02
Stussa

Don't put padding in the 'li' item. Instead set the anchor tag to display:inline-block; and apply padding to it.

suren

Define your anchor tag css property as:

{display:block}

Then the anchor will occupy the entire list area, so your click will work in the empty space next to your list.

Make the anchor tag contain the padding rather than the li. This way, it will take up all the area.

Sabby62

Use following:

a {
  display: list-item;
  list-style-type: none;
}

Super, super late to this party, but anyway: you can also style the anchor as a flex item. This is particularly useful for dynamically sized/arranged list items.

a {
  /* This flexbox code stretches the link's clickable 
   * area to fit its parent block. */
  display:        flex;
  flex-grow:      1;
  flex-shrink:    1;
  justify-content: center;
}

(Caveat: flexboxes are obvs still not well supported. Autoprefixer to the rescue!)

Or you could use jQuery:

$("li").click(function(){
   window.location=$(this).find("a").attr("href"); 
   return false;
});

You should use this CSS property and value into your li:

pointer-events:all;

So, you can handle the link with jQuery or JavaScript, or use an a tag, but all other tag elements inside the li should have the CSS property:

pointer-events:none;

You can always wrap the whole tag li in with the hiperlink tag Here is my solution:

#nav {
  background-color: #181818;
  margin: 0px;
  overflow: hidden;
}

#nav img {
  float: left;
  padding: 5px 10px;
  margin-top: auto;
  margin-bottom: auto;
  vertical-align: bottom;
}

#nav ul {
  list-style-type: none;
  margin: 0px;
  background-color: #181818;
  float: left;
}

#nav li {
  display: block;
  text-align: center;
  float: left;
  width: 40px;
  padding: 25px 10px;
}

#nav li:hover {
  background-color: #785442;
}

#nav a {
  color: white;
  font-family: Helvetica, Arial, sans-serif;
  text-decoration: none;
}
<div id="nav">
  <img src="/images/renderedicon.png" alt="Icon" height="57" width="57" />
  <ul>
    <a href="#"><li>One1</li></a>
    <a href="#"><li>Two</li></a>
    <a href="#"><li>Three</li></a>
    <a href="#"><li>Four</li></a>
  </ul>
</div>
<div>
  <h2>Heading</h2>
</div>
Spudious

Put the list item within the hyperlink instead of the other way round.

For example with your code:

<a href="#"><li>One</li></a>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!