在搜索如何在CSS中居中放置form元素时,我发现必须将margin设置为auto,然后设置width属性。但是,width在这里代表了什么呢?
例如,当我将width设置为350px时,我会使表单居中,而当我将其设置为5px时,我不会使表单居中。
你能在这里解释一下width代表什么吗?
谢谢。
发布于 2011-10-01 21:24:39
width是显示元素时元素本身的宽度,需要设置宽度,以便浏览器能够自动计算元素周围的边距,使其居中显示。至于为什么5px的值不能居中元素,350px的值不能居中,我不太确定,我从来没有遇到过这个问题,也许只是因为表单不能重新调整到这么小的大小,所以浏览器会自动将它的宽度更改为auto。
发布于 2011-10-01 23:21:07
这里有一个简单的测试来展示发生了什么:
HTML
/* This form will be 200px and centered within its parent element */
<form></form>
/* #formsection is 300px and not centered. The form it contains will be
200px and centered withint #formsection */
<div id="formsection">
<form></form>
</divCSS
/* All forms will be 200px and centered in their parent container */
form {
width: 200px;
margin: 0 auto;
border: 1px solid red;
}
/* #formsection is 300px in width and not centered */
#formsection {
width: 300px;
border: 1px solid blue;
}
#formsection form {
border: 1px solid green;
}您可以看到一个demo of it here。
您已经提到,width不会更改元素的宽度。如果你的<form>有一个比你设置的宽度更宽的子元素(也就是你的5px案例),这是可能的。要进行测试,请将border或background-color添加到您的子元素中,并检查是否有溢出表单的元素。
另一个更快的选择是使用火狐的Web Developer addon。安装完成后,CTRL+SHIFT+Y将显示您悬停在其上的任何元素的样式信息。
https://stackoverflow.com/questions/7620467
复制相似问题