我的中心元素还有一个小问题。我想到了我之前提出的问题,但我似乎找不到这个问题的答案。我有以下示例代码来演示我的问题。
<div id="main" style="width: 960px;">
<form>
<label>Test</label>
<input type="text" value="Test" id="inputfield" />
</form>
....
</div>
现在我尝试将它作为块元素使用宽度和边距来正确定位,但不知怎的,它失败了。我是否需要使用id字段,或者是否建议我在每个输入文本字段周围放置一个div(使用#main input[type=text]{...}
)?
答案 0 :(得分:2)
对于这种情况,最好的方法是根据ID #inputfiled
在CSS Demo
中添加此内容#inputfield { display: block; margin: 0 auto; }
在跨浏览器兼容性方面,依赖input[type="text"]
等属性选择器是非常危险的。
如果您想要将所有输入元素居中,而不是其他输入元素,则可以使用名称选择器
input,select,textarea { /* These three elements round up all the input types */
display: block;
margin: 0 auto;
}
答案 1 :(得分:0)
when centering this way,您需要添加width
input{
display:block;
margin:0 auto;
width:100px;
}
答案 2 :(得分:0)
使用以下css并确保添加宽度。
<style type="text/css">
#inputfield {
display: block;
margin: 0 auto;
width: 200px;
}
</style>