大家好,我是前端架构师,关注微信公众号【程序员大卫】免费领取前端精品资料。
背景
在使用 CSS 时,许多人缺乏深入研究,遇到问题时往往通过叠加属性试探效果,哪个属性有效就用哪个。
对于何时设置 width: 100% 和 height: 100%,不少人感到困惑。本文将深入探讨这两个 CSS 属性的正确使用时机。
什么时候设置 width: 100%
首先需要明确一个问题:元素的宽度由什么决定?
1. 块级元素(display: block)
块级元素的宽度通常由其父元素的宽度决定。因此,一般不需要显式设置 width: 100%。
注: 这里提到的
父元素实际上是为了便于理解,更准确的说法是包含块。关于“包含块”的详细概念,请参考:什么是 CSS包含块?
<style>
.box {
background: red;
}
</style>
<div class="box">
1-啦啦啦啦啦啦
<br />
2-啊啊啊
</div>
特殊情况
当元素设置 position: absolute 时,会脱离文档流。此时,它的宽度不再受父元素控制。
.box {
position: absolute;
}
因此需要显式设置 width: 100% 以让其占满父容器的宽度。
.box {
position: absolute;
width: 100%;
}
2. 行内元素(display: inline)
行内元素的宽度由其内容决定,width 属性对其无效。因此,即使设置了 width: 100%,效果也不会发生变化。
.box {
display: inline;
width: 100%;
}
上例中,无论是否设置 width: 100%,元素的宽度都不会改变。
3. 行内块级元素(display: inline-block)
行内块级元素的宽度默认由其内容决定。但与行内元素不同,width 属性对其生效。
.box {
display: inline-block;
}
如果设置 width: 100%,可以使其占满父容器的宽度。
.box {
display: inline-block;
width: 100%;
}
注意:
img和input元素默认是inline-block。
4. 在 Flex 容器中的内层元素
当父元素 .box 使用了 display: flex 时,内层的 .inner 元素默认并不会自动撑满父容器的宽度。
例如下面的代码中:
<div class="box">
<div class="inner">
1-啦啦啦啦啦啦
<br />
2-啊啊啊
</div>
</div>
<style>
.box {
display: flex;
border: 1px solid blue;
}
.box .inner {
background-color: red;
}
</style>
为了让 .inner 撑满 .box 的宽度,需要显式地设置 width: 100%:
.box .inner {
background-color: red;
width: 100%;
}
什么时候设置 height: 100%
同样需要先明确:元素的高度由什么决定?
通常情况下,元素的高度由内容撑开。开发中需要设置 height: 100% 的场景主要有以下两种:
1. 全屏布局
当需要实现全屏布局时,需确保 html 和 body 的高度都为 100%,这样内容高度设置了100%才能占满整个视口。
<style>
html, body {
height: 100%;
}
.box {
background: red;
height: 100%;
}
</style>
<div class="box">
1-啦啦啦啦啦啦
<br />
2-啊啊啊
</div>
2. 滚动区域
在某些情况下,需要为内容区域设置滚动条。例如,当父元素具有固定高度,而子元素内容超出时,设置 height: 100% 可以让子元素高度等于父元素,并通过 overflow: auto 实现滚动效果。
为什么需要两层结构来实现滚动,而不是直接让
box这一层滚动?通常,我们会将box这一层封装成组件,并设置height: 100%让其继承组件引用层的高度,从而确保滚动行为的可控性和复用性。
<style>
.parent {
width: 150px;
height: 100px;
}
.box {
background: red;
height: 100%;
overflow: auto;
}
</style>
<div class="parent">
<div class="box">
1-啦啦啦啦啦啦
<br />
2-啊啊啊
<br />
3-啊啊啊
<br />
4-啊啊啊
<br />
5-啊啊啊
<br />
6-啊啊啊
<br />
7-啊啊啊
<br />
8-啊啊啊
</div>
</div>
总结
- 宽度: 对于大多数块级元素,其宽度由父元素决定,通常无需设置
width: 100%。只有当元素脱离文档流(如position: absolute)时,才需设置width: 100%。 - 高度: 元素的高度通常由内容撑开。如果需要使高度由父元素决定,则需设置
height: 100%。
希望这篇文章能帮助你更好地理解和使用 CSS 的 width 和 height 属性!
最后
点赞👍 + 关注➕ + 收藏❤️ = 学会了🎉。
更多优质内容关注公众号,@前端大卫。