Stretching tag to fill entire
  • 2020-01-26 06:54发布

    Here's a simple menu structure:

    <ul id="menu">
      <li><a href="javascript:;">Home</a></li>
      <li><a href="javascript:;">Test</a></li>
    </ul>
    

    I want the <a> to be stretched so that it fills the entire <li>. I tried using something like width: 100%; height: 100% but that had no effect. How do I stretch the anchor tag correctly?

    标签: html css xhtml
    10条回答
    Viruses.
    2楼-- · 2020-01-26 07:16

    I used this code to fill the width and height 100%

    HTML

    <ul>
        <li>
            <a>I need to fill 100% width and height!</a>
        </li>
    <ul>
    

    CSS

    li a {
       display: block;
       height: 100%; /* Missing from other answers */
    }
    
    查看更多
    不美不萌又怎样
    3楼-- · 2020-01-26 07:18

    Just changing the display property to block didn't work for me. I removed the padding of li and set the same padding for a.

      li a {
            display:block;  
            padding: 4px 8px;  
    
      }
    
    查看更多
    女痞
    4楼-- · 2020-01-26 07:18

    If your <li>s had to have a specific height then your <a>s would only stretch to the <li>'s width and not the height anymore. One way I solve this is to use CSS display:block and add paddings to my <a>s OR wrap the <a>s around the <li>s

    <ul id="menu">
          <a href="javascript:;"><li>Home</li></a>
          <a href="javascript:;"><li>Test</li></a>
        </ul>   
    
    查看更多
    成全新的幸福
    5楼-- · 2020-01-26 07:24

    Just style the A with a display:block;:

    ul#menu li a { display: block;}
    
    查看更多
    家丑人穷心不美
    6楼-- · 2020-01-26 07:28

    The "a" tag is an inline level element. No inline level element may have its width set. Why? Because inline level elements are meant to represent flowing text which could in theory wrap from one line to the next. In those sorts of cases, it doesn't make sense to supply the width of the element, because you don't necessarily know if it's going to wrap or not. In order to set its width, you must change its display property to block, or inline-block:

    a.wide {
        display:block;
    }
    
    ...
    
    <ul id="menu">
      <li><a class="wide" href="javascript:;">Home</a></li>
      <li><a class="wide" href="javascript:;">Test</a></li>
    </ul>
    

    If memory serves, you can set the width on certain inline level elements in IE6, though. But that's because IE6 implements CSS incorrectly and wants to confuse you.

    查看更多
    姐就是有狂的资本
    7楼-- · 2020-01-26 07:28
    <!doctype html>
    <html>
    <head>
    <style type="text/css">
    #wide li a {
        display:block;
    }
    </style> 
    </head>
    <body>
        <ul id="menu">
          <li><a href="javascript:;">Home</a></li>
          <li><a href="javascript:;">Test</a></li>
        </ul>
    </body>
    </html>
    

    You should try to avoid using a class on every tag so your content remains easy to maintain.

    查看更多
    登录 后发表回答