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条回答
    2楼-- · 2020-01-26 07:30

    A different approach:

    <ul>
        <li>
            <a></a>
            <img>
            <morestuff>TEXTEXTEXT</morestuff>
        </li>
    </ul> 
    
    a {
        position: absolute;
        top: 0;
        left: 0;
        z-index: [higher than anything else inside parent]
        width:100%;
        height: 100%;
    }  
    

    This is helpful if the link's container also has images and such inside of it, or is of potentially different sizes depending on image / content size. With this, the anchor tag itself can be empty, and you can arrange other elements inside of anchor's container however you want. Anchor will always match the size of the parent, and will be on top, to make the entire li clickable.

    查看更多
    做自己的国王
    3楼-- · 2020-01-26 07:36

    Use line-height and text-indent instead of padding for li element, and use display: block; for anchor tag

    查看更多
    家丑人穷心不美
    4楼-- · 2020-01-26 07:37
    display:flex
    

    is the HTML5 way.

    See Fiddle

    Useful to hack frameworks buttons, or any other element, but you may need to remove their padding first, and set them to the desired height.

    In this case, angular-material tabs, which are kind of tricky to make them work as a "standard" website nav.

    Notice that the pointer changes as soon as you enter the tab : the < a > are now stretched to fit their parent dimensions.

    Out of topic, notice how flawless angular-material displays the ripple effect, even on a "large surface".

    .md-header{
    /* THIS IS A CUSTOM HEIGHT */
        height: 50vh !important; /* '!important' IS JSFIDDLE SPECIFIC */
    }
    
    md-tab{    
        padding: 0 !important; /* '!important' IS JSFIDDLE SPECIFIC */
    }
    
    a{
        display: flex;
        align-items: center;
        justify-content: center; 
        height: 100%; 
    }
    

    UPDATE 2018

    AngularJS Material throws a (gentle) warning when using flex on button elements, so don't assume all HTML elements/tags can handle display:flex properly, or have a homogeneous behaviour across browsers.

    Remember to consult flexbugs in case of unexpected behaviour in a particular browser.

    查看更多
    够拽才男人
    5楼-- · 2020-01-26 07:38

    I wanted this functionality only on tab view i.e below 720px, so in media query I made:

    @media(max-width:720px){
      a{
        display:block;
        width:100%;
      }
    }
    
    查看更多
    登录 后发表回答