Css width for div

Ширина (width) и высота (height) в HTML

В этой статье рассмотрим, как можно задавать ширину и какими свойствами стоит делать это. Для первого примера возьмём блочный элемент div. По умолчанию он имеет высоту равную нулю (если ничего не содержит) и занимает 100% ширины родительского элемента. Попробуем задать ему ширину в 200 пикселей и высоту в 150. Для этого используем CSS свойства width (ширина) и height (высота):

Можно задавать ширину не только в пикселях, но и в процентах от ширины родительского элемента. Попробуем сделать это:

К сожалению, задать высоту для блочного элемента в процентах не получится. Если написать «height:50%;», то в разных браузерах будет диаметрально противоположный результат, поэтому лучше считать такую запись ошибкой.

Только у одного элемента можно задать свойство height в процентах, а точнее у псевдоэлементов :before и ::after. Читайте о них в статье Псевдоэлементы (:before, ::after)

Максимальная и минимальная ширина (max-width и min-width)

Жёсткое ограничение ширины — это не лучший способ строить сайт. Потому что в таком случае появятся проблемы с адаптацией под мобильные и планшеты: ширина экрана может быть меньше ширины блока. Тогда часть сайта будет выходить пределы вёрстки сайта и появится горизонтальная прокрутка, чего у версии сайта на мобильном быть не должно. Поэтому вместо жёсткого задания ширины используется ограничение сверху через CSS свойство max-width. Мы знаем, что блочный элемент div пытается занять всю ширину родительского элемента, как будто по умолчанию у него есть свойство width и оно имеет значение 100%.

Но теперь, если вы возьмёте окно своего браузера и сузите до 400 пикселей и меньше, то увидите как контейнер div уменьшает свои размеры, чтобы не выпрыгивать за пределы вёрстки. Если же изменить «max-width:400px;» на «width:400px», то блок будет выходить за пределы родительского элемента:

По смыслу свойство min-width является диаметрально противоположным к max-width. Оно ограничивает минимальную ширину элемента, но не ограничивает максимальную.

Максимальная и минимальная высота (max-height и min-height)

Для блока div можно задать максимальную высоту. Это делается в том случае, если контента в блоке будет слишком много и есть вероятность, что он испортит вёрстку сайта. Ведь у контейнера div высота изменяется автоматически в зависимости от того, сколько занимает места его дочерние элементы.

Рассмотрим наглядный пример необходимости использования max-height. Допустим, что нам надо сделать чат, где пользователи сайта смогут обмениваться текстовыми сообщениями. Для этого нужно создать контейнер, который будет расти по мере появления в нём новых сообщений. Но как только div достигает определённой высоты, то перестаёт расти и появится полоса прокрутки. Используем следующий CSS код:

 
Тише, мыши, кот на крыше, а котята ещё выше. Кот пошёл за молоком, а котята кувырком. Кот пришёл без молока, а котята ха-ха-ха.

Весь текст не вместится в div. Поэтому из-за свойства «overflow-y: scroll;» появится полоса прокрутки:

Тише, мыши, кот на крыше, а котята ещё выше. Кот пошёл за молоком, а котята кувырком. Кот пришёл без молока, а котята ха-ха-ха.

Благодаря атрибуту contenteditable=»true» у тега div в примере, Вы можете изменить текст внутри контейнера. Попробуйте удалить и добавить несколько строк. Размер контейнера будет подстраиваться под количества текста в нём до тех пор, пока не станет быть равен 100px. Затем появится полоса прокрутки.

Читайте также:  Host your html website

По смыслу свойство min-height является диаметрально противоположным к max-height. Оно ограничивает минимальную высоту элемента, но не ограничивает максимальную.

Источник

CSS Height, Width and Max-width

The CSS height and width properties are used to set the height and width of an element.

The CSS max-width property is used to set the maximum width of an element.

CSS Setting height and width

The height and width properties are used to set the height and width of an element.

The height and width properties do not include padding, borders, or margins. It sets the height/width of the area inside the padding, border, and margin of the element.

CSS height and width Values

The height and width properties may have the following values:

  • auto — This is default. The browser calculates the height and width
  • length — Defines the height/width in px, cm, etc.
  • % — Defines the height/width in percent of the containing block
  • initial — Sets the height/width to its default value
  • inherit — The height/width will be inherited from its parent value

CSS height and width Examples

Example

Set the height and width of a element:

Example

Set the height and width of another element:

Note: Remember that the height and width properties do not include padding, borders, or margins! They set the height/width of the area inside the padding, border, and margin of the element!

Setting max-width

The max-width property is used to set the maximum width of an element.

The max-width can be specified in length values, like px, cm, etc., or in percent (%) of the containing block, or set to none (this is default. Means that there is no maximum width).

The problem with the above occurs when the browser window is smaller than the width of the element (500px). The browser then adds a horizontal scrollbar to the page.

Using max-width instead, in this situation, will improve the browser’s handling of small windows.

Tip: Drag the browser window to smaller than 500px wide, to see the difference between the two divs!

Читайте также:  Adding property to javascript object

Note: If you for some reason use both the width property and the max-width property on the same element, and the value of the width property is larger than the max-width property; the max-width property will be used (and the width property will be ignored).

Example

This element has a height of 100 pixels and a max-width of 500 pixels:

Try it Yourself — Examples

Set the height and width of elements
This example demonstrates how to set the height and width of different elements.

Set the height and width of an image using percent
This example demonstrates how to set the height and width of an image using a percent value.

Set min-width and max-width of an element
This example demonstrates how to set a minimum width and a maximum width of an element using a pixel value.

Set min-height and max-height of an element
This example demonstrates how to set a minimum height and a maximum height of an element using a pixel value.

All CSS Dimension Properties

Property Description
height Sets the height of an element
max-height Sets the maximum height of an element
max-width Sets the maximum width of an element
min-height Sets the minimum height of an element
min-width Sets the minimum width of an element
width Sets the width of an element

Источник

width

The width CSS property sets an element’s width. By default, it sets the width of the content area, but if box-sizing is set to border-box , it sets the width of the border area.

Try it

The specified value of width applies to the content area so long as its value remains within the values defined by min-width and max-width .

  • If the value for width is less than the value for min-width , then min-width overrides width .
  • If the value for width is greater than the value for max-width , then max-width overrides width .

Syntax

/* values */ width: 300px; width: 25em; /* value */ width: 75%; /* Keyword values */ width: max-content; width: min-content; width: fit-content(20em); width: auto; /* Global values */ width: inherit; width: initial; width: revert; width: revert-layer; width: unset; 

Values

Defines the width as a distance value.

Defines the width as a percentage of the containing block’s width.

The browser will calculate and select a width for the specified element.

The intrinsic preferred width.

The intrinsic minimum width.

Uses the fit-content formula with the available space replaced by the specified argument, i.e. min(max-content, max(min-content, )) .

Accessibility concerns

Ensure that elements set with a width aren’t truncated and/or don’t obscure other content when the page is zoomed to increase text size.

Formal definition

Initial value auto
Applies to all elements but non-replaced inline elements, table rows, and row groups
Inherited no
Percentages refer to the width of the containing block
Computed value a percentage or auto or the absolute length
Animation type a length, percentage or calc();

Formal syntax

width =
auto |
|
min-content |
max-content |
fit-content( )

=
|

Examples

Default width

p class="goldie">The Mozilla community produces a lot of great software.p> 

Example using pixels and ems

.px_length  width: 200px; background-color: red; color: white; border: 1px solid black; > .em_length  width: 20em; background-color: white; color: red; border: 1px solid black; > 
div class="px_length">Width measured in pxdiv> div class="em_length">Width measured in emdiv> 

Example with percentage

.percent  width: 20%; background-color: silver; border: 1px solid red; > 
div class="percent">Width in percentagediv> 

Example using «max-content»

p.maxgreen  background: lightgreen; width: intrinsic; /* Safari/WebKit uses a non-standard name */ width: -moz-max-content; /* Firefox/Gecko */ width: -webkit-max-content; /* Chrome */ width: max-content; > 
p class="maxgreen">The Mozilla community produces a lot of great software.p> 

Example using «min-content»

p.minblue  background: lightblue; width: -moz-min-content; /* Firefox */ width: -webkit-min-content; /* Chrome */ width: min-content; > 
p class="minblue">The Mozilla community produces a lot of great software.p> 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 18, 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.

Источник

CSS width Property

The width of an element does not include padding, borders, or margins!

Note: The min-width and max-width properties override the width property.

Default value: auto
Inherited: no
Animatable: yes. Read about animatable Try it
Version: CSS1
JavaScript syntax: object.style.width=»500px» Try it

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

CSS Syntax

Property Values

Value Description Demo
auto Default value. The browser calculates the width Demo ❯
length Defines the width in px, cm, etc. Read about length units Demo ❯
% Defines the width in percent of the containing block Demo ❯
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

More Examples

Example

Set the width of an element using a percent value:

Example

Set the width of an element to 100px. However, when it gets focus, make it 250px wide:

input[type=text]:focus width: 250px;
>

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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