在这个系列里我会为大家讲解一些前端面试里有关css的常考题。在面试官问到我们有关css的问题时,很有可能会问到这些问题。
什么是页面的响应式
所谓页面的响应式就是,无论用户使用的是PC端、移动端、还是平板电脑,页面都能够跟随着用户的设备和屏幕尺寸的变化,能够自动的适配用户的设备。
如何实现页面的响应式
- 使用百分比(常适用于外层大容器)
// html
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
// css
*{
margin: 0;padding: 0; //将所有元素的外边距和内边距设置为 0
}
li:nth-child(1){
background-color: antiquewhite;
}
li:nth-child(2){
background-color: rgb(232, 93, 38);
}
li:nth-child(3){
background-color: rgb(64, 248, 40);
}
ul{
width: 100%; //继承父容器的全部大小
}
li{
width: 50%;
text-align: center;
}
以这段代码为例,创建了一个宽度为 100% 的无序列表,其中包含三个宽度为 50% 的列表项,每个列表项有不同的背景颜色,列表项中的内容居中显示,并且这个无序列表会随着页面大小的改变而响应式的变化。
- flex
// html
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
// css
*{
margin: 0;padding: 0; //将所有元素的外边距和内边距设置为 0
}
ul{
display: flex; //弹性布局使列表项沿着水平方向排列。
justify-content: center; //使得列表项在水平方向上居中对齐。
align-items: center; //使得列表项在垂直方向上居中对齐
}
li{
list-style: none;
width: 200px;
height: 100px;
text-align: center; // 文本水平居中对齐
}
li:nth-child(1){
background-color: antiquewhite;
}
li:nth-child(2){
background-color: rgb(232, 93, 38);
}
li:nth-child(3){
background-color: rgb(64, 248, 40);
}
这段代码通过使用弹性布局,创建了一个水平居中且列表项垂直居中的无序列表。每个列表项都具有指定的尺寸和背景颜色,且列表项内的数字文本居中显示。
值得注意的是:flex适用于某个容器内的响应式,但不太适合用于整个页面的响应式,并不能适用于实际开发中的所有场景。
- rem + 媒体查询(适用于任何场景)
// html
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
// css
*{
margin: 0;padding: 0;
}
li:nth-child(1){
background-color: antiquewhite;
}
li:nth-child(2){
background-color: rgb(232, 93, 38);
}
li:nth-child(3){
background-color: rgb(64, 248, 40);
}
li{
width: 10rem; //设置了每个列表项的宽度为10rem
text-align: center;
}
@media screen and (min-width: 1000px){
html{
font-size: 30px; //当屏幕宽度大于1000px时,根元素字体大小设置为30px。
}
}
@media screen and (min-width: 800px) and (max-width: 1000px){
html{
font-size: 20px; //当屏幕宽度在800px到1000px之间时,根元素字体大小设置为20px。
}
}
@media screen and (max-width: 500px){
html{
font-size: 14px; //当屏幕宽度小于500px时,根元素字体大小设置为14px。
}
}
rem是相对于根元素(html)的字体大小的单位,使用媒体查询来调整根元素字体大小的方法,进而会影响rem单位的元素的尺寸。这种方法可以在实现页面的响应式的同时,比直接使用媒体查询的代码量少。
- 直接媒体查询(适用于任何场景)
// html
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
// css
*{
margin: 0;padding: 0;
}
li:nth-child(1){
background-color: antiquewhite;
}
li:nth-child(2){
background-color: rgb(232, 93, 38);
}
li:nth-child(3){
background-color: rgb(64, 248, 40);
}
li{
list-style: none;
width: 200px;
height: 100px;
text-align: center;
}
@media screen and (min-width: 1000px){
li{
width: 300px;
}
}
@media screen and (min-width: 800px) and (max-width: 1000px) {
li{
width: 200px;
}
}
@media screen and (max-width: 500px){
li{
width: 100px;
}
}
媒体查询能够使页面适配用户所使用的设备,但是直接使用媒体查询的代码量较多。
- vw/vh (常适用于外层大容器)
// html
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
// css
*{
margin: 0;padding: 0;
}
li:nth-child(1){
background-color: antiquewhite;
}
li:nth-child(2){
background-color: rgb(232, 93, 38);
}
li:nth-child(3){
background-color: rgb(64, 248, 40);
}
li{
width: 20vw;
text-align: center;
}
vw是视口宽度的百分比,vh是视口高度的百分比。通过使用vw和vh这百分比单位可以实现页面的响应式布局,能够使页面元素的尺寸根据用户的视口大小来进行动态的调整。