Javascript div 100 height

Особенности свойства height в %

Обычно свойство height , указанное в процентах, означает высоту относительно внешнего блока.

Однако, всё не так просто. Интересно, что для произвольного блочного элемента height в процентах работать не будет!

Чтобы лучше понимать ситуацию, рассмотрим пример.

Пример

Наша цель – получить вёрстку такого вида:

При этом блок с левой стрелкой должен быть отдельным элементом внутри контейнера.

Это удобно для интеграции с JavaScript, чтобы отлавливать на нём клики мыши.

То есть, HTML-код требуется такой:

Как это реализовать? Подумайте перед тем, как читать дальше…

Придумали. Если да – продолжаем.

Есть разные варианты, но, возможно, вы решили сдвинуть .toggler влево, при помощи float:left (тем более что он фиксированной ширины) и увеличить до height: 100% , чтобы он занял всё пространство по вертикали.

Вы ещё не видите подвох? Смотрим внимательно, что будет происходить с height: 100% …

Демо height:100% + float:left

.container < border: 1px solid black; >.content < /* margin-left нужен, так как слева от содержимого будет стрелка */ margin-left: 35px; >.toggler < /* Зададим размеры блока со стрелкой */ height: 100%; width: 30px; float: left; background: #EEE url("arrow_left.png") center center no-repeat; border-right: #AAA 1px solid; cursor: pointer; >

А теперь – посмотрим этот вариант в действии:

Как видно, блок со стрелкой вообще исчез! Куда же он подевался?

Ответ нам даст спецификация CSS 2.1 пункт 10.5.

«Если высота внешнего блока вычисляется по содержимому, то высота в % не работает, и заменяется на height:auto . Кроме случая, когда у элемента стоит position:absolute .»

В нашем случае высота .container как раз определяется по содержимому, поэтому для .toggler проценты не действуют, а размер вычисляется как при height:auto .

Какая же она – эта автоматическая высота? Вспоминаем, что обычно размеры float определяются по содержимому (10.3.5). А содержимого-то в .toggler нет, так что высота нулевая. Поэтому этот блок и не виден.

Если бы мы точно знали высоту внешнего блока и добавили её в CSS – это решило бы проблему.

Источник

Особенности свойства height в %

Обычно свойство height , указанное в процентах, означает высоту относительно внешнего блока.

Однако, всё не так просто. Интересно, что для произвольного блочного элемента height в процентах работать не будет!

Чтобы лучше понимать ситуацию, рассмотрим пример.

Пример

Наша цель – получить вёрстку такого вида:

При этом блок с левой стрелкой должен быть отдельным элементом внутри контейнера.

Это удобно для интеграции с JavaScript, чтобы отлавливать на нём клики мыши.

То есть, HTML-код требуется такой:

Как это реализовать? Подумайте перед тем, как читать дальше…

Придумали. Если да – продолжаем.

Есть разные варианты, но, возможно, вы решили сдвинуть .toggler влево, при помощи float:left (тем более что он фиксированной ширины) и увеличить до height: 100% , чтобы он занял всё пространство по вертикали.

Вы ещё не видите подвох? Смотрим внимательно, что будет происходить с height: 100% …

Демо height:100% + float:left

.container < border: 1px solid black; >.content < /* margin-left нужен, так как слева от содержимого будет стрелка */ margin-left: 35px; >.toggler < /* Зададим размеры блока со стрелкой */ height: 100%; width: 30px; float: left; background: #EEE url("arrow_left.png") center center no-repeat; border-right: #AAA 1px solid; cursor: pointer; >

А теперь – посмотрим этот вариант в действии:

Как видно, блок со стрелкой вообще исчез! Куда же он подевался?

Ответ нам даст спецификация CSS 2.1 пункт 10.5.

«Если высота внешнего блока вычисляется по содержимому, то высота в % не работает, и заменяется на height:auto . Кроме случая, когда у элемента стоит position:absolute .»

В нашем случае высота .container как раз определяется по содержимому, поэтому для .toggler проценты не действуют, а размер вычисляется как при height:auto .

Какая же она – эта автоматическая высота? Вспоминаем, что обычно размеры float определяются по содержимому (10.3.5). А содержимого-то в .toggler нет, так что высота нулевая. Поэтому этот блок и не виден.

Если бы мы точно знали высоту внешнего блока и добавили её в CSS – это решило бы проблему.

Источник

Javascript div 100 height

Last updated: Jan 11, 2023
Reading time · 3 min

banner

# Set the Width and Height of an Element using JavaScript

Use the style.width and style.height properties to set the width and height of an element, e.g. box.style.width = ‘100px’ .

The width and height properties set the element’s width and height to the supplied values.

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> div id="box" style="background-color: salmon">Box 1div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const box = document.getElementById('box'); // ✅ Set width to 100px box.style.width = '100px'; // ✅ Set height to 100px box.style.height = '100px';

The style object allows us to set, read or update any CSS property on the element.

Copied!
const box = document.getElementById('box'); // ✅ Set width to 100px box.style.width = '100px'; // ✅ Set height to 100px box.style.height = '100px'; console.log(box.style.width); // 👉️ "100px" console.log(box.style.height); // 👉️ "100px"

# Setting width and height has no effect on inline elements

Note that setting the width and height on an inline element, such as a span has no effect.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> span id="box" style="background-color: salmon">Box 1span> script src="index.js"> script> body> html>

And here is our attempt to update the element’s height and width.

Copied!
const box = document.getElementById('box'); // ❌ Set width to 100px box.style.width = '100px'; // ❌ Set height to 100px box.style.height = '100px';

If you open your browser, you will see that the element’s width and height are determined by the content area.

# Setting the element’s display to inline-block

To solve this, we can set the element’s display property to inline-block .

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> span id="box" style="background-color: salmon; display: inline-block" >Box 1span > script src="index.js"> script> body> html>

And now we can set the element’s width and height.

Copied!
const box = document.getElementById('box'); // ✅ Set width to 100px box.style.width = '100px'; // ✅ Set height to 100px box.style.height = '100px';

Some examples use the setAttribute method to update the element’s height and width, however, the setAttribute method overrides the style property completely.

Copied!
const box = document.getElementById('box'); box.setAttribute('style', 'width: 100px; height: 100px');

The setAttribute method takes 2 parameters:

  1. The name of the attribute we want to set on the element.
  2. The value that should be assigned to the attribute.

If the attribute already exists, the value is updated, otherwise, a new attribute is added with the specified name and value.

So if you use the setAttribute method approach, you are effectively replacing the element’s style attribute value.

This can be very confusing and difficult to debug, so it’s best to set any CSS properties using the style object on the element.

# Set the Width and Height on a Collection of Elements

If you need to set the width and height on a collection of elements, you have to:

  1. Select the collection of elements.
  2. Use the for. of method to iterate over the collection.
  3. Set the width and height using the style.width and style.height property on each element.
Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div class="box" style="background-color: salmon">Box 1div> div class="box" style="background-color: salmon">Box 2div> div class="box" style="background-color: salmon">Box 3div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const boxes = document.querySelectorAll('.box'); for (const box of boxes) box.style.width = '100px'; box.style.height = '100px'; >

We used the document.querySelectorAll method to select all elements with a class of box .

We then used the for. of loop to iterate over the collection and set the width and height properties on each element.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Читайте также:  Поделиться вконтакте код html
Оцените статью