CSS: Inline element stretch to fill available horizontal space of container

前端 未结 3 1357
情书的邮戳
情书的邮戳 2021-02-05 07:16

For example I have a 200px div containing three buttons, the text is only minimal so the buttons don\'t fill the horizontal space available. Is it possible to..

3条回答
  •  余生分开走
    2021-02-05 07:49

    Similar to Roberts:

    HTML

    CSS

    div#container {
        border: solid 1px;
        width: 200px;
    }
    
    div#container button {
        width: 33%;
    }
    
    div#container button:last-child {
        width: 34%;
    }
    

    That doesn't allow for a fluid layout: #container width must be known, then you do the math.

    To allow for a fluid layout you need to hop into the world of absolute positioning:

    div#container {
        border: solid 1px;
        width: 50%; /* resize your browser window to see results */
    
        position: relative;
    }
    
    div#container button {
        position: absolute;
        width: 50px;
    }
    
    button#one {
        top: 0;
        left: 0;
    }
    
    button#two {
        top: 0;
        left: 55px;
    }
    
    button#three {
        width: auto !important; /* get rid of the 50px width defined earlier */
        top: 0;
        left: 110px;
        right: 0px;
    }
    

    Watch out for the height of #container. It's gone since all it's children in this example are absolutely positioned--you can see that from the border.

提交回复
热议问题