× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

how to center align the label for form

sheriffderek
Dec 29, 2016
<p>There are a few ways you can do this. Here is a fiddle: <a href="https://jsfiddle.net/sheriffderek/b9jg33b3/" rel="nofollow">https://jsfiddle.net/sheriffderek/b9jg33b3/</a></p> <h2>Markup</h2> <pre><code>&lt;form action="" class="your-thing"&gt; &lt;label class="input-w"&gt; &lt;span class="label"&gt;First&lt;br&gt; name:&lt;/span&gt; &lt;input type="text" placeholder='sheriff'&gt; &lt;/label&gt; &lt;label class="input-w"&gt; &lt;span class="label"&gt;Last name:&lt;/span&gt; &lt;input type="text" placeholder='derek'&gt; &lt;/label&gt; &lt;/form&gt; </code></pre> <p><br></p> <h2>1. With <code>display: inline-block;</code></h2> <p>The trick is that you need the element to be display inline-<strong>block</strong>. This way, you can use the <code>vertical-align: middle;</code> property of inline elements - and have the other properties of block elements too. Also, you don't want to use floats in this case. So, </p> <pre><code>.inline-block .input-w { display: block; // to stack them width: 100%; } .inline-block .label, .inline-block input { /* float: none; you may need this to overide previous float rules */ display: inline-block; vertical-align: middle; } </code></pre> <p><br></p> <h2>2. The other way would be to use flexbox <code>display: flex;</code></h2> <p>This involves a little more concern about the markup and the parent of these inputs.</p> <pre><code>.flex-box { display: flex; flex-direction: column; } .flex-box .input-w { display: flex; flex-direction: row; } </code></pre> <p>They both have their strengths and side-affects. : )</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/38278619/how%20to%20center%20align%20the%20label%20for%20form/38278954">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus