How to get current screen width in CSS?

I use the following CSS code for formatting when the screen width is less than 480 pixels and it works well.

@media screen and (min-width: 480px) { body { background-color: lightgreen; } } 

I would like to get the current calculation width for using zoom , as it follows from:

 @media screen and (min-width: 480px) { body { background-color: lightgreen; zoom: (current screen width)/(480); } } 
+10
source share
3 answers

Use the CSS3 percent view feature.

Percentage Explanation

Assuming you want the width of the body to be proportional to the browser viewing port. I added a border so you can see the size of the body when changing the width or height of the browser. I used a ratio of 90% of the view port size.

 <!DOCTYPE html> <html lang="en"> <head> <title>Styles</title> <style> @media screen and (min-width: 480px) { body { background-color: skyblue; width: 90vw; height: 90vh; border: groove black; } div#main { font-size: 3vw; } } </style> </head> <body> <div id="main"> Viewport-Percentage Test </div> </body> </html> 

+27
source

Based on your requirements, I think that you want to put dynamic fields in a CSS file, however this is not possible since CSS is a static language. However, you can model the behavior with Angular.

Please refer to the example below. I show only one component here.

login.component.html

 import { Component, OnInit } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { cssProperty:any; constructor(private sanitizer: DomSanitizer) { console.log(window.innerWidth); console.log(window.innerHeight); this.cssProperty = 'position:fixed;top:' + Math.floor(window.innerHeight/3.5) + 'px;left:' + Math.floor(window.innerWidth/3) + 'px;'; this.cssProperty = this.sanitizer.bypassSecurityTrustStyle(this.cssProperty); } ngOnInit() { } } 

login.component.ts

 <div class="home"> <div class="container" [style]="cssProperty"> <div class="card"> <div class="card-header">Login</div> <div class="card-body">Please login</div> <div class="card-footer">Login</div> </div> </div> </div> 

login.component.css

 .card { max-width: 400px; } .card .card-body { min-height: 150px; } .home { background-color: rgba(171, 172, 173, 0.575); } 
+1
source

As mentioned in this post , this is not possible. You can create separate .css files for different types of media and process them using javascript. Take a look at this artcile: How to use media queries in JavaScript

-2
source

Source: https://habr.com/ru/post/1242986/


All Articles