Как сделать ширину блока по содержимому css
Перейти к содержимому

Как сделать ширину блока по содержимому css

  • автор:

Box-sizing

Свойство box-sizing позволяет указать как ведут себя размеры блока при наличии рамок и полей. Применяются к элементам, у которых заданы размеры.

content-box — отступы и рамки рисуются снаружи блока блока и увеличивают его размеры (значение по умолчанию).

padding-box — рамки рисуются снаружи блока блока и увеличивают его размеры, padding отрисовывается внутри элемента и не влияет на размеры. Работал только в Firefox, на ноябрь 2018 уже не поддерживается.

border-box — элемент сохраняет заданные размеры, отступы и рамки отрисовываются внутрь элемента.

How to make div width expand with its content using CSS ?

Given an HTML document and the task is to make div width expand with its content using CSS. To do this, the width property is used to set the width of an element excluding padding, margin and border of element. The width property values are listed below:

Syntax:

Property Values:

  • width: auto; It is used to set width property to its default value. If the width property set to auto then the browser calculates the width of element.
  • width: length; It is used to set the width of element in form of px, cm etc. The length can not be negative.
  • width: initial; It is used to set width property to its default value.
  • width: inherit; It is used to set width property from its parent element.

Example 1: This example use width: auto; property to display the content.

Как сделать, чтобы ширина div зависела от содержимого?

Пробовал float: left, но в данном случае это работает только в IE и Opera.

Как есть

Как хотелось бы — работает в IE и Opera с float: left

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

  • Вопрос задан более трёх лет назад
  • 118795 просмотров
  • Facebook
  • Вконтакте
  • Twitter

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

Как видите, этот код составлен по принципам, обеспечивающим обратную совместимость с Firefox 2 и IE 6 и 7.

Если рамка внешнего блока не будет совершенно прилегать ко границам внутренних строчных блоков, тогда непременно попробуйте и внешний блок также оформить в качестве строчного блока, то есть и ему назначить класс «lineBlock», описанный вышеприведённым

box-sizing

The box-sizing CSS property sets how the total width and height of an element is calculated.

Try it

By default in the CSS box model, the width and height you assign to an element is applied only to the element’s content box. If the element has any border or padding, this is then added to the width and height to arrive at the size of the box that’s rendered on the screen. This means that when you set width and height , you have to adjust the value you give to allow for any border or padding that may be added. For example, if you have four boxes with width: 25%; , if any has left or right padding or a left or right border, they will not by default fit on one line within the constraints of the parent container.

The box-sizing property can be used to adjust this behavior:

  • content-box gives you the default CSS box-sizing behavior. If you set an element’s width to 100 pixels, then the element’s content box will be 100 pixels wide, and the width of any border or padding will be added to the final rendered width, making the element wider than 100px.
  • border-box tells the browser to account for any border and padding in the values you specify for an element’s width and height. If you set an element’s width to 100 pixels, that 100 pixels will include any border or padding you added, and the content box will shrink to absorb that extra width. This typically makes it much easier to size elements. box-sizing: border-box is the default styling that browsers use for the <table> , <select> , and <button> elements, and for <input> elements whose type is radio , checkbox , reset , button , submit , color , or search .

Note: It is often useful to set box-sizing to border-box to lay out elements. This makes dealing with the sizes of elements much easier, and generally eliminates a number of pitfalls you can stumble on while laying out your content. On the other hand, when using position: relative or position: absolute , use of box-sizing: content-box allows the positioning values to be relative to the content, and independent of changes to border and padding sizes, which is sometimes desirable.

Syntax

The box-sizing property is specified as a single keyword chosen from the list of values below.

Values

This is the initial and default value as specified by the CSS standard. The width and height properties include the content, but does not include the padding, border, or margin. For example, .box renders a box that is 370px wide.

Here, the dimensions of the element are calculated as: width = width of the content, and height = height of the content. (Borders and padding are not included in the calculation.)

The width and height properties include the content, padding, and border, but do not include the margin. Note that padding and border will be inside of the box. For example, .box renders a box that is 350px wide, with the area for content being 330px wide. The content box can’t be negative and is floored to 0, making it impossible to use border-box to make the element disappear.

Here the dimensions of the element are calculated as: width = border + padding + width of the content, and height = border + padding + height of the content.

Formal definition

Initial value content-box
Applies to all elements that accept width or height
Inherited no
Computed value as specified
Animation type discrete

Formal syntax

Examples

Box sizes with content-box and border-box

This example shows how different box-sizing values alter the rendered size of two otherwise identical elements.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *