将表单元素居中时,这些 CSS 属性意味着什么?
在搜索如何在 CSS
中将 form
元素居中时,我发现必须将 margin
设置为 auto
然后设置 width
属性。但是,这里的 width
代表什么?
例如,当我将 width
设置为 350px
时,我会将表单置于中心,而当将其设置为 5px
时,我不会不要让它居中。
您能解释一下 width
这里代表什么吗?
谢谢。
While searching for how to center a form
element in CSS
, I found that I have to set margin
to auto
and then set a width
property. But, what does width
represent here?
When I for example set the width
to 350px
I get the form to the center, while when setting it to 5px
for example, I don't get it centered.
Can you kindly explain what width
represents here?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
width 是元素显示时本身的宽度,需要设置该宽度,以便浏览器能够自动计算元素周围的边距,使其显示居中。至于为什么 5px 的值不能使元素居中,而 350px 的值不能居中,我不确定,我从未遇到过这个问题,也许只是表单无法调整那么小,所以它会自动更改由浏览器设置为 auto 的宽度。
width is the width of the element itself when it is displayed, the width is required to be set so that the browser will be able to automatically calculate the margins around the element so that it will appear centered. As for why a value of 5px doesn't center the element and 350px does I'm not sure, I've never encountered that problem, perhaps it's just that the form can't be re-sized that small so it is automatically changed by the browser to a width of auto.
这是一个简单的测试来显示发生了什么:
HTML
CSS
您可以看到 此处演示。
您曾提到
width
不会更改元素宽度。如果您的另一种更快的替代方法是使用 Web Developer 插件对于火狐浏览器。安装后,
CTRL+SHIFT+Y
将显示您将鼠标悬停在其上的任何元素的样式信息。Here's a simple test to show what's happening:
HTML
CSS
You can see a demo of it here.
You had mentioned that
width
isn't changing the element width. This is possible if your<form>
has a child element that is wider than the width you set on it (i.e. your5px
case). To test, add aborder
orbackground-color
to your child elements and check if any are overflowing the form.Another, faster, alternative is to use the Web Developer addon for Firefox. Once it's installed,
CTRL+SHIFT+Y
will show the style information of any element you hover over.