Search code examples
htmlcssalignment

Align labels in form next to input


I have very basic and known scenario of form where I need to align labels next to inputs correctly. However I don't know how to do it.

My goal would be that labels are aligned next to inputs to the right side. Here is picture example of desired result.

enter image description here

I have made a fiddle for your convenience and to clarify what I have now - http://jsfiddle.net/WX58z/

Snippet:

<div class="block">
    <label>Simple label</label>
    <input type="text" />
</div>
<div class="block">
    <label>Label with more text</label>
    <input type="text" />
</div>
<div class="block">
    <label>Short</label>
    <input type="text" />
</div>


Solution

  • While the solutions here are workable, more recent technology has made for what I think is a better solution. CSS Grid Layout allows us to structure a more elegant solution.

    The CSS below provides a 2-column "settings" structure, where the first column is expected to be a right-aligned label, followed by some content in the second column. More complicated content can be presented in the second column by wrapping it in a <div>.

    [As a side-note: I use CSS to add the ':' that trails each label, as this is a stylistic element - my preference.]

    /* CSS */
    
    div.settings {
        display:grid;
        grid-template-columns: max-content max-content;
        grid-gap:5px;
    }
    div.settings label       { text-align:right; }
    div.settings label:after { content: ":"; }
    <!-- HTML -->
    
    <div class="settings">
        <label>Label #1</label>
        <input type="text" />
    
        <label>Long Label #2</label>
        <span>Display content</span>
    
        <label>Label #3</label>
        <input type="text" />
    </div>