什么是自适应?
定义
自适应是一套代码能够自动适配各个终端。一次设计,普遍适用。
自适应方案
使用百分比
<style>
.box {
width: 100vw;
height: 100vh;
.inner-box {
width: 20%;
height: 20%;
background: cadetblue;
}
}
</style>
使用rem,resize
rem的原理是根据父组件的fontsize来计算rem的单位长度。可以通过监听window的resize,动态修改fontsize,进而影响rem,最终达到自适应的效果
resize.js
const resize=()=>{
//与原来1080的比值
let scale=window.innerHeight/1080;
document.documentElement.style.fontSize=`${32*scale}px`;
console.log('resize');
}
const scaleListener=()=>{
window.addEventListener('resize',resize);
console.log('scaleListening');
}
export {
scaleListener
}
Remandresizeselfadaption.vue
<template>
<div class="remandresizeselfadaption">
内容提示
</div>
</template>
<script>
import { scaleListener } from './resize';
export default{
mounted(){
scaleListener();
}
}
</script>
媒体查询语句
@media screen and (max-width:300px){
html{
width:300px;
font-size:12px;
}
}
@media screen and (max-width:500px){
html{
width:500px;
font-size:20px;
margin:0 auto;
}
}
flex布局
<template>
<div class="home">
<img src="../assets/vue.svg" alt="Vue logo">
<div class="flex-test">
<div class="div1">图片1</div>
<div class="div2">图片2</div>
<div class="div3">图片3</div>
<div class="div4">图片4</div>
</div>
</div>
</template>
<script>
export default{
}
</script>
<style scoped>
.flex-test {
display: flex;
flex-direction: row;
width: 60vw;
height: 50vh;
}
.div1 {
width: 20%;
background-color: cadetblue;
display: flex;
align-items: center;
justify-content: center;
}
.div2 {
width: 20%;
background-color: darkgray;
display: flex;
align-items: center;
justify-content: center;
}
.div3 {
width: 20%;
background-color: darkolivegreen;
display: flex;
align-items: center;
justify-content: center;
}
.div4 {
width: 20%;
background-color: green;
display: flex;
align-items: center;
justify-content: center;
}
</style>