CSS子宽度100%或px问题
也许一个简单的问题有一个简单的答案。
今天我想知道当子级的宽度与父级的宽度完全相同时,以 px 为单位的子级宽度或 100% 之间有什么区别。我知道结果是一样的,但是最好使用什么?
例子;
div {width: 300px;}
h1 {width: 300px;} /*or..*/
h1 {width: 100%;}
<div>
<h1>Width of child</h1>
</div>
有关系吗?你用哪个?
Maybe a simple question with an easy answer.
I wondered today what is the difference between a child width in px or 100%, when the child is going to be the exact same width as the parent. The outcomes will be the same I know, but what is best to use?
Example;
div {width: 300px;}
h1 {width: 300px;} /*or..*/
h1 {width: 100%;}
<div>
<h1>Width of child</h1>
</div>
Does it matter? And which do you use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从视觉上看,您的两个示例看起来都是一样的。
但是对子元素使用 width: 100% 意味着如果您想更改两者的宽度,只需更改父元素的宽度即可。
另请注意,ah* 标签是块级元素,因此默认情况下,它已设置为 100% 宽度,因此在您的示例中,为 h1 设置任何宽度都是多余的。
Visually, both of your examples will look the same.
But using width: 100% for the child element means if you ever want to change the width of both, you only need to change the width of the parent element.
Also note that a h* tags are block-level elements, so, by default, it's already set to 100% width, so in your example, setting any width for h1 is redundant.
如果您使用 100%,那么随着父级宽度的变化,随着时间的推移,修改会减少一次。所以使用 100% 会让你的 CSS 更易于维护。
If you use 100%, then that's one less modification over time as the width of the parent changes. So using 100% makes your CSS more maintainable.
有一个更好的替代方案:
...在子元素上。
对于您的示例,使用 {width:100%} 或 {width:300px},如果您决定向子级 (h1) 应用内边距或边框,那么它将溢出到其容器之外。如果您使用像素宽度,那么您需要从子项的宽度中减去(padding-left + padding-right + border-left + border-right)之和,以使其恰好适合内部,舒适。在百分比宽度的情况下,您必须进行严格的计算才能得出正确的百分比(并且可能仍然有点偏差)。
但是 {width:auto} 会自动考虑填充和边框,并且其计算出的宽度将比容器小适当的量,以便 H1 上边框的外边缘恰好位于 div 的内容区域内。
There is a much better alternative to both:
...on the child element.
For your example, with either {width:100%} or {width:300px}, if you decided to then apply padding or a border to the child (h1), then it will overflow outside its container. In you use pixel-width, then you would need to subtract the sum of (padding-left + padding-right + border-left + border-right) from the width of the child to get it to just fit inside, snug. In the case of percentage-width, you would have to do a squirely calculation to come up with the correct percentage (and probably still be a tad off).
But {width:auto} will automatically account for padding and border, and its computed width will be the appropriate amount less than the container, so that the outer edge of the border on H1 stays just within the content area of your div.
另一个例子:它可能会对您实际应用固定大小背景图像的元素产生影响。在这种情况下请使用 px,这样布局的修改就不会破坏您的图像。正如巴巴克已经说过的,它只与以后的修改相关。
Another example: it could make a difference to which element you'd actually apply a fixed size background image. Use px in that case so modifications on layout would not break your images. As Babak already said, it's only relevant for later modifications.