- CSS calc width and height values
- 2 Answers 2
- Функция calc()
- Интерактивный пример
- Синтаксис
- Формальный синтаксис
- Примеры
- Позиционирование объекта в окне с помощью отступа
- Автоматическое изменение размера формы ввода для соответствия размеру контейнера
- Вложенный calc() с CSS переменными
- Спецификации
- Поддержка браузерами
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- How to get current screen width in CSS?
CSS calc width and height values
How can I calc, using css, the screen height and use the returned value for the width calculation? is it possible at all?
2 Answers 2
Yes, in css there is a thing called vh (viewport height) and vw (viewport width). The viewport is the screen.
@torazaburo I updated the answer as I’ve seen some of my mistakes. Do you think the now updated version would work?
So what is the correct way? why is there a need to reduce 33.5px? I saw it in other places as well, is there a reason for it?
@KBE You said that you wanted the returned value of the calc() operation in height. So heightReturnedValue = 0.5vh — 33.5px
on CSS, It is not even possible, on javascript you would not have any problem, I would recommend the use of other varial values such as width: 100vw relative of width of the window, height:100vh relative of height of window, max-width: & min-width: and max-height: & min-height: with width:50% or height:50% your element is auto resize and have limits. You can also take advantage of elements such as the ::after and ::before that are relative to the father and get for example borders triangulars.
If you would put more information we could find the exact code for your problem.
method to do it with javascript can be like this
// onresize event for responsive document.getElementsByTagName("BODY")[0].onresize=function() < element = document.getElementById("you_element"); element.style.height = 'calc(50% - 33.5px)'; calculateHeight = parseInt(element.clientHeight) * 1.3 element.style.width = calculateHeight + 'px' document.getElementById("width").innerHTML = calculateHeight; document.getElementById("height").innerHTML = element.clientHeight; >// onload page for one set document.getElementsByTagName("BODY")[0].onload=function()
Функция calc()
calc() — это функция CSS, которая даёт возможность рассчитать значения свойств CSS во время их определения. Она может быть использована везде, где применимы , (en-US), , , , или .
Интерактивный пример
Синтаксис
Функция calc() принимает в качестве параметра математическое выражение, результат вычисления которого можно использовать как значение CSS-свойства. Выражение может включать операторы +, -, *, / с использованием стандартных правил приоритета операторов:
Умножение. По крайней мере хоть один из сомножителей должен быть .
Деление. Делитель должен быть .
Примечание: Деление на ноль выдаст ошибку при парсинге HTML.
Примечание: Операторы + и — всегда должны быть по обеим сторонам отделены пробелом. Выражение calc(50% -8px) будет интерпретировано как величина в процентах и следующее за ним отрицательное число в пикселях (не верное выражение), в то время как calc(50% — 8px) — правильное выражение, будет интерпретировано как вычитание из процентов длины в пикселях. Операторы * и / не требуют отделения от операндов знаком пробела, но это не запрещено и даже приветствуется.
Формальный синтаксис
Примеры
Позиционирование объекта в окне с помощью отступа
calc() делает простым позиционирование объекта с помощью отступа. В этом примере создаётся баннер занимающий в ширину все окно с отступами по краям в 40px.
.banner position: absolute; left: 5%; /* для браузеров не поддерживающих calc() */ left: calc(40px); width: 90%; /* для браузеров не поддерживающих calc() */ width: calc(100% - 80px); border: solid black 1px; box-shadow: 1px 2px; background-color: yellow; padding: 6px; text-align: center; >
div class="banner">Это баннер!div>
Автоматическое изменение размера формы ввода для соответствия размеру контейнера
В следующем случае calc() помогает обеспечить не выпадание полей формы за края блока, задав отступ.
Давайте посмотрим некоторый код CSS:
input padding: 2px; display: block; width: 98%; /* для браузеров, не поддерживающих calc() */ width: calc(100% - 1em); > #formbox width: 130px; /* для браузеров, не поддерживающих calc() */ width: calc(100% / 6); border: 1px solid black; padding: 4px; >
Здесь ширина формы становится 1/6 от ширины окна. Затем, чтобы задать размер полей, мы вновь используем функцию calc() , которая вычитает 1em из ширины блока. Теперь применим этот CSS к следующему HTML-коду:
form> div id="formbox"> label>Type something:label> input type="text"> div> form>
Вложенный calc() с CSS переменными
Вы также можете использовать calc() с CSS переменными. Рассмотрим пример кода:
.foo --widthA: 100px; --widthB: calc(var(--widthA) / 2); --widthC: calc(var(--widthB) / 2); width: var(--widthC); >
Спецификации
Поддержка браузерами
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 11 февр. 2023 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
How to get current screen width in CSS?
Assuming you want the body width size to be a ratio of the browser’s view port. I added a border so you can see the body resize as you change your browser width or height. I used a ratio of 90% of the view-port size.
Viewport-Percentage Test
Just as we have the css unit «view-height(vh)», which roughly corresponds to the height of the viewport, you can also use view-width(vw) to dynamically resize your element with respect to the width of the viewport
this can be achieved with the css calc() operator
@media screen and (min-width: 480px) < body < background-color: lightgreen; zoom:calc(100% / 480); >>
Based on your requirement I think you want to put dynamic fields in CSS file, however that is not possible as CSS is a static language. However you can simulate the behaviour by using Angular.
Please refer to the below example. I’m here showing only one component.
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
login.component.css