链接用填充包裹li

时间:2016-12-14 16:47:22

标签: html css list css-selectors

我有一个包含大量列表项的无序列表。一些列表项是链接,有些则不是。我想在列表项中添加填充,因此外观是一致的,无论它是否是链接,即我不想添加填充到锚点,而是添加到列表和锚点以包围链接AND填充。

尽管在悬停时使用display:block,但背景颜色仅在链接内的文本周围。它忽略了填充。有没有办法让链接包含填充(没有在链接上添加填充)?



ul li {
  float: left;
  line-height: 5em;
  padding: 0 2em;
}
a:link {
  display: block;
}
a:visited {
  display: block;
}
a:hover {
  display: block;
  background-color: rgb(245, 245, 245);
}
a:active {
  display: block;
  background-color: rgb(245, 245, 245);
}

<ul>
  <li><a href="1.html">Item 1</a>
  </li>
  <li><a href="2.html">Item 2</a>
  </li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li><a href="5.html">Item 5</a>
  </li>
</ul>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您可以使用hover li代替a来更正background-color上应用的hover,方法是:

li:hover a {
  display: block;
}
li:hover {
  background-color: rgb(245, 245, 245);
}

而不是:

a:hover { 
  display:block; 
  background-color:rgb(245,245,245);
}

见下面的演示:

ul li {
  float: left;
  line-height: 5em;
  padding: 0 2em;
}
a:link {
  display: block;
}
a:visited {
  display: block;
}
li:hover a {
  display: block;
}
li:hover {
  background-color: rgb(245, 245, 245);
}
a:active {
  display: block;
  background-color: rgb(245, 245, 245);
}
<ul>
  <li><a href="1.html">Item 1</a>
  </li>
  <li><a href="2.html">Item 2</a>
  </li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li><a href="5.html">Item 5</a>
  </li>
</ul>

答案 1 :(得分:0)

在这里,我的评论应该解释一切,但随时可以问。

<ul>
    <li><a href="1.html">Item 1</a></li>
    <li><a href="2.html">Item 2</a></li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li><a href="5.html">Item 5</a></li>
</ul>  

ul{
    list-style-type: none;  /* Feel free to remove this, just easier without bullets */
}

ul li {
    float: left;    
    line-height: 5em;       /* Should be the same as height */
    padding: 0 2em;
    position: relative;     /* Make sure a & a:before can stay contained */
    height: 5em;            /* Should be same as line-height */
    white-space: nowrap;    /* Ensure that your items don't wrap and mess up width */
    z-index: -1;            /* So that a:before is able to trigger with :hover */
}

a{
    position: relative;     /* Make sure a:before can stay contained */
    display: block;         /* Ensures that a can expand to full size of container */
}

a:before{ 
    content: "";            /* Necessary for :before element to be created */
    position: absolute;     /* Vital - allows positioning */
    top: 0; 
    right: -2em;        /* Minus same padding as li has */
    bottom: 0;
    left: -2em;         /* Minus same padding as li has */
    z-index: -1;            /* Makes sure :before doesn't go above anchor text */
}

a:hover:before,
a:active:before { 
    background-color:rgb(245,245,245); 
}