Styles

Как получить текущую ширину экрана в CSS?

Я использую следующий код CSS для форматирования, когда ширина экрана меньше 480 пикселей, и он работает хорошо.

@media screen and (min-width: 480px) < body < background-color: lightgreen; >> 
@media screen and (min-width: 480px) < body < background-color: lightgreen; zoom: (current screen width)/(480); >> 

zoom только для IE. теперь в CSS используется transform:scale(xx) — person dippas &nbsp schedule 14.02.2016

Ответы (4)

Используйте функцию CSS3 Viewport-percent. Объяснение процента просмотра Предполагая, что вы хотите, чтобы размер ширины тела был пропорциональным порту просмотра браузера. Я добавил рамку, чтобы вы могли видеть изменение размера тела при изменении ширины или высоты браузера. Я использовал соотношение 90% от размера окна просмотра.

       
Viewport-Percentage Test

Используйте Полная страница, чтобы увидеть эффект масштабирования. — person Heather92065; 20.02.2016

@media screen and (min-width: 480px) < body < background-color: lightgreen; zoom:calc(100% / 480); >> 

Исходя из вашего требования, я думаю, вы хотите поместить динамические поля в файл CSS, однако это невозможно, поскольку CSS является статическим языком. Однако вы можете имитировать поведение с помощью Angular. Пожалуйста, обратитесь к приведенному ниже примеру. Я здесь показываю только один компонент. логин.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() < >> 

Точно так же, как у нас есть css единица высоты просмотра (vh), которая примерно соответствует высоте области просмотра, вы также можете использовать view-width(vw) для динамического изменения размера вашего элемента по отношению к ширине области просмотра. i.e

Источник

How to get current screen width in css in Html?

HTML is a markup language used to structure and display content on the web. CSS, or Cascading Style Sheets, is used to control the layout and appearance of elements on a web page.

Читайте также:  article

To get the current screen width in CSS, there are a few different methods that can be used. Here are three examples:

Method 1: Using the width property

For example, if you want to target the body element, you would add the following code to your CSS file:

In this example, we are setting the width of the body element to 100%, which will make it the same width as the screen.

Method 2: Using JavaScript

For example, if you want to target the body element, you would add the following code to your HTML file:

var screenWidth = window.innerWidth;
  • Step 3 — Use the getElementById method to target the element you want to set the width of, and the style property to set the width
document.getElementById("myBody").style.width = screenWidth + "px";

This will set the width of the element with the id «myBody» to the current screen width.

Method 3: Using media queries

This media query will apply the CSS inside the curly braces only when the screen width is 600px or less.

@media (max-width: 600px) < body < width: 100%; >> @media (min-width: 601px) and (max-width: 900px) < body < width: 80%; >>

This will set the width of the body element to 100% when the screen width is 600px or less, and 80% when the screen width is between 601px and 900px.

These are just a few examples of how to get the current screen width in CSS. Depending on your specific use case and the tools you are using, there may be other methods that are more appropriate. The important thing is to understand the concepts behind each method, and how to apply them to your specific project.

It is worth noting that the method you choose will depend on what you are trying to achieve and the tools you are using. The width property method is a simple and straight forward method that doesn’t require any additional tools or libraries, and is supported by all modern browsers. However, it has a limitation in that it can only be used to set the width of a single element.

Читайте также:  Скомпилировать python код в exe

The JavaScript method is a more dynamic and flexible method that can be used to set the width of multiple elements and can be combined with other JavaScript code to create more complex interactions. However, it does require some knowledge of JavaScript and can be more complex to implement.

The media query method is a powerful tool that allows you to create responsive designs that adjust to different screen sizes. This method is also supported by all modern browsers, but it can be complex to implement if you have many different screen sizes to target.

In any case, It’s important to note that these examples are not the only ways to get current screen width in CSS, and there are other ways to achieve this.

For example, you can use libraries such as Bootstrap, Foundation or Bulma, which are pre-made collections of CSS and JavaScript that can help you quickly create responsive designs.

In addition, you can use the CSS variables(custom properties) to store the width and use it across your css.

It’s a good practice to try different ways and choose the one that best fits your project’s requirements.

Conclusion

To summarize, there are several ways to get the current screen width in CSS, including using the width property, JavaScript, and media queries. Each method has its own advantages and limitations, and the choice of which method to use will depend on the specific requirements of your project. The width property method is a simple and straightforward method that is supported by all modern browsers, while the JavaScript method is more flexible and dynamic but requires some knowledge of JavaScript. The media query method is a powerful tool for creating responsive designs that adjust to different screen sizes but can be complex to implement. Additionally, you can use pre-made libraries such as Bootstrap, Foundation, or Bulma, or even CSS variables to store and use the width across your CSS. It’s a good practice to try different approaches and choose the one that best fits your project’s requirements.

Читайте также:  Узнать полный путь до файла python

Источник

Как найти ширину экрана и применить его к конкретному css

Мне нужно найти ширину экрана пользователя и применить эту ширину к стилю.

Мне нужно поместить ширину в css с помощью JavaScript или любых других параметров.

Как я могу это сделать?
Благодарим вас за помощь.

Чтобы получить разрешение экрана, используйте объект screen :

document.getElementById("container").style.width = screen.width + "px"; 

Чтобы получить ширину окна браузера (для всех браузеров, кроме IE6 и ниже, в противном случае отметьте этот метод кросс-браузера) используйте:

document.getElementById("container").style.width = window.innerWidth + "px"; 

Также обратите внимание, что script следует вызывать только при полном загрузке документа.

Для этого мультимедийных запросов CSS лучше всего. Напишите вот так:

@media screen and (max-width: 980px) < #container< background: #ccc; >> 

Я считаю, что вы ищете именно это. приведенный ниже код поможет вам захватить ширину или высоту для всех браузеров.

function getViewPortSize() < var viewportwidth; var viewportheight; // Standard browsers if (typeof window.innerWidth != 'undefined') < viewportwidth = window.innerWidth, viewportheight = window.innerHeight >// IE6 else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) < viewportwidth = document.documentElement.clientWidth, viewportheight = document.documentElement.clientHeight >//Older IE else < viewportwidth = document.getElementsByTagName('body')[0].clientWidth, viewportheight = document.getElementsByTagName('body')[0].clientHeight >return viewportwidth + "~" + viewportheight; > 

установить ширину контейнера

убедитесь, что контейнер загружен до js. я думаю, что правильный синтаксис

Я думаю, если вы просто хотите, чтобы div заполнил ширину окна браузера. вы можете просто использовать css

Источник

Оцените статью