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;
}