CSS 基础
取值单位
外观样式
布局样式
动画样式
工具与规范
实例练习
宽高
width
与 height
样式能分别设置元素的宽度与高度。
$$tip
width
与 height
样式对行内元素不起效。
$$
<iframe height="300" style="width: 100%" scrolling="no" title="flexbox" src="https://codepen.io/3yya/embed/KKyeWaX?default-tab=css%2Cresult&editable=true&theme-id=light" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"></iframe>
关键字属性
width
和 height
属性还有三个特殊的关键字属性值:
- max-content:固有首选长度,表示为元素允许的最大长度。
- min-content:固有最小长度,表示为元素允许的最小长度。
- fit-content:尽可能在不溢出的情况下选择接近
max-content
的长度,至少为min-content
的长度,公式为:min(max-content, max(min-content, 可用长度))
<div class="container">
<div class="min-content">min-content say hello to 三眼鸭</div>
<div class="max-content">max-content say hello to 三眼鸭</div>
<div class="fit-content">fit-content say hello to 三眼鸭</div>
</div>
<style>
.container {
background-color: teal;
width: 160px;
}
.min-content,
.max-content,
.fit-content {
background-color: pink;
margin: 20px 0;
}
.min-content {
width: min-content;
}
.max-content {
width: max-content;
}
.fit-content {
width: fit-content;
}
</style>
$$demo <div class="container"> <div class="min-content">min-content say hello to 三眼鸭</div> <div class="max-content">max-content say hello to 三眼鸭</div> <div class="fit-content">fit-content say hello to 三眼鸭</div> </div> <style> body { padding: 1px; } .container { background-color: teal;
width: 160px;
}
.min-content,
.max-content,
.fit-content {
background-color: pink;
margin: 20px 0;
}
.min-content {
width: min-content;
}
.max-content {
width: max-content;
}
.fit-content {
width: fit-content;
}
</style>
$$
最小宽高
min-width
与 min-height
样式用以设置元素的最小宽度与最小高度。
$$tip
min-width
与 min-height
的优先级高于 width
与 height
,当两者冲突时以min-width
与 min-height
为先。
$$
<iframe height="300" style="width: 100%" scrolling="no" title="flexbox" src="https://codepen.io/3yya/embed/yLPEMov?default-tab=css%2Cresult&editable=true&theme-id=light" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"></iframe>
最大宽高
max-width
与 max-height
样式用以设置元素的最大宽度与最大高度。
$$tip
max-width
与 max-height
的优先级高于 width
与 height
,当两者冲突时以max-width
与 max-height
为先。
$$
<iframe height="300" style="width: 100%" scrolling="no" title="flexbox" src="https://codepen.io/3yya/embed/JjOZWvq?default-tab=css%2Cresult&editable=true&theme-id=light" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"></iframe>
练习
- 设置一个
div
的背景色为pink
,高度为100px
, 宽度为100%
, 最大宽度为800px
,并通过拖动浏览器的宽度理解其中的效果。 - 设置一个
div
的背景色为pink
,高度为100px
, 宽度为100%
, 最小宽度为800px
,并通过拖动浏览器的宽度理解其中的效果。