March 19, 2012

How to center an input[type=text] while leaving all the other elements uncenterred?

Question by Snowflake

I have another small problem with centering elements. I thought about the previous questions that I’ve asked, but I can’t seem to find the answer on this problem. I have the following example code to demonstrate my problem.

<div id="main" style="width: 960px;">
    <form>
        <label>Test</label>
        <input type="text" value="Test" id="inputfield" />
    </form>
    ....
</div>

Now I tried to treat it as a block-element using width and margin to position it correctly, but somehow it failed. Do I need to use an id field or is it recommanded that I put a div around every input text field (using #main input[type=text]{...})?

Answer by Starx

For this case, the best way would be assigning specific rule as per the id #inputfiled

Add this in the CSS Demo

#inputfield { display: block; margin: 0 auto; }

Relying on attribute selectors like input[type="text"] is very risky in terms of cross-browser compatibility.


Updates

In case you want to center all input elements, but not other, you can use a name selector

input,select,textarea { /* These three elements round up all the input types */
    display: block; 
    margin: 0 auto; 
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!