Search code examples
htmlcssinputlabelstylesheet

Getting everything on 1 line filled up


I'm working with unsemantic grid to create my layout. Well I have a container where I have a Label and an inputtext. The label has a width of 20% then a margin-rightof 1em then I want to have the rest of the space in the container to be filled by the inputfield, basically it should be like this

[LABEL width: 20%] [margin-left:1em] [Remaining space on this line should be filled by the inputfield]

The problem I have is, label and margin have succeeded. But I have to give the inputfield width of 80% so it will on the line but whe resizing it isn't filling up the line again.

I made a small quick fiddle jsfiddle.net/Mg8cY/

When make the browser smaller it breaks and it becomes 2 lines, when expanding the browser it doesn't fill up the line. I'm trying to get a pure css solution here.


Solution

  • You can't do exactly what you're asking for with CSS alone, but there are some ways to get very close. First, with box-sizing: border-box, it's possible to make the label subtract the 1em gap from its own width, leaving the input with exactly 80% of the width:

    .lbl {
        -moz-box-sizing: border-box;
        -webkit-box-sizing: border-box;
        box-sizing: border-box; 
        width: 20%;
        display: inline-block;
        padding-right: 1em;
    }
    input[type=text],input[type=password] {
        width: 79%;
    }
    

    jsFiddle: http://jsfiddle.net/Mg8cY/2/

    Alternately, you could use display: table and display: table-cell to divide up the widths. Input elements don't respect most values of display, but if you add an extra HTML tag around the input, you can make this work. It's also necessary to add an extra (empty) tag between the label and the input to hold the 1em margin, since table cells can't have margin and include their padding in their width.

    <span class="lbl">mail</span>
    <span></span>
    <span><input type="text" placeholder="Email"></span>
    
    .grid-75 p {
        display: table;
        width: 100%;
    }
    .grid-75 p span {
        display: table-cell;
    }
    input[type=text],input[type=password] {
        width: 100%;
    }
    .lbl {
        width: 20%;
    }
    .lbl + span{
        width: 1em; /* also needs the same font size as the label */
    }
    

    jsFiddle: http://jsfiddle.net/Mg8cY/4/