Angular 12 :如何在组件样式中编写媒体查询?

283 阅读1分钟

这是一个关于如何在Angular风格组件和风格标签中编写媒体查询的简短教程。

Angular组件中的媒体查询可以获得以下好处

  • 响应式网页设计
  • 移动优先的用户体验设计

CSS中的媒体查询有助于针对特定尺寸的样式--桌面、移动、平板和拥抱尺寸。媒体查询需要为每个设备的分辨率写一个不同的断点 不同设备的尺寸

设备宽度
纵向模式的手机最小宽度:320px
横向模式的手机最小宽度:480px
纵向的平板电脑和iPad最小宽度:600px
横向平板电脑和iPad最小宽度:801px
笔记本电脑和台式机最小宽度:1025px
高分辨率台式机最小宽度:1281px

如果你想为台式机和笔记本设备应用这些样式,你可以在css中应用以下样式

@media only screen and (max-width: 1025px) { 
   .div{
       color:red;
   }
}

Angular 12引入了styles 标签来包含scss样式

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],

  // Supported from angular version12
  styles: [
    `
    @media only screen and (max-width: 1025px) { 
   .div{
       color:red;
   }
}
    
    `
  ]
})
export class AppComponent {
  title = 'angular app';
}

app.component.css

  @media screen and (max-width: 1025px) {
      /* Here are some changes*/
    }

   /* Mobile device styles */
    @media screen and (max-width: 480px) {
          /* Here are some changes*/
    }

    ```