Css как не учитывать padding

box-sizing

CSS свойство box-sizing определяет как вычисляется общая ширина и высота элемента.

Интерактивный пример

По умолчанию в блоковой модели CSS ширина и высота, которую вы задаёте элементу применяется только для контента элемента. Если у элемента есть граница или внутренний отступ, то они добавляются к ширине и высоте, чтобы получить отображаемый на экране размер. Это значит, что когда вы выставляете ширину и высоту, вам придётся изменять значение, при добавлении границ и отступов. Например, если у вас есть четыре блока с width: 25%; , и у какого-нибудь из них есть граница или внутренний отступ слева или справа, то по умолчанию они не поместятся на одной строке.

Свойство box-sizing может изменять это поведение:

  • content-box даёт стандартное поведение свойства box-sizing. Если вы выставите элементу ширину 100 пикселей, то ширина его контента будет 100 пикселей, а ширина границ и внутренних отступов при рендере будет добавлена к финальной ширине, делая элемент шире ста пикселей.
  • border-box говорит браузеру учитывать любые границы и внутренние отступы в значениях, которые вы указываете в ширине и высоте элемента. Если вы выставите элементу ширину 100 пикселей, то эти 100 пикселей будут включать в себя границы и внутренние отступы, а контент сожмётся, чтобы выделить для них место. Обычно это упрощает работу с размерами элементов.

**Примечание:**Часто выставление box-sizing: border-box полезно для размещения элементов. Оно сильно упрощает работу с размерами элементов, и как правило устраняет ряд подводных камней, на которые вы можете наткнуться, размещая контент. С другой стороны, используя position-relative или position: absolute , box-sizing: content-box позволяет позиционным значениям быть зависимыми только от контента, а не от границ и отступов, что иногда желательно.

Синтаксис

Для свойства box-sizing устанавливается единственное ключевое слово из списка значений ниже.

Читайте также:  Javascript background color names

Значения

Это значение по умолчанию, определённое в CSS стандарте. Свойства width и height включают исключительно контент, и не включают padding и border. Например .box будет иметь ширину 370 пикселей.Размеры элемента рассчитываются следующим образом: width = ширина контента, и height = высота контента. (Границы и внутренние отступы не включаются в вычисление.)

Свойства width и height включают контент, внутренний отступ и границы, но не включают внешний отступ. Заметьте, что внутренний отступ и граница будут внутри блока. Например, .box будет иметь общую ширину 350 пикселей, а ширина контента составит 330 пикселей. Размер контента не может быть отрицательным, минимальное значение — 0, поэтому border-box невозможно использовать для скрытия элемента.Размеры элемента рассчитываются следующим образом: width = граница + внутренний отступ + ширина контента, и height = граница + внутренний отступ + высота контента.

Формальный синтаксис

Примечание: Значение padding-box устарело

Пример

Этот пример показывает как разные значения box-sizing изменяют видимый размер двух идентичных элементов.

HTML

div class="content-box">Content boxdiv> br> div class="border-box">Border boxdiv> 

CSS

div  width: 160px; height: 80px; padding: 20px; border: 8px solid red; background: yellow; > .content-box  box-sizing: content-box; /* Total width: 160px + (2 * 20px) + (2 * 8px) = 216px Total height: 80px + (2 * 20px) + (2 * 8px) = 136px Content box width: 160px Content box height: 80px */ > .border-box  box-sizing: border-box; /* Total width: 160px Total height: 80px Content box width: 160px - (2 * 20px) - (2 * 8px) = 104px Content box height: 80px - (2 * 20px) - (2 * 8px) = 24px */ > 

Результат

Спецификации

Начальное значение content-box
Применяется к все элементы, которые могут иметь ширину и высоту
Наследуется нет
Обработка значения как указано
Animation type discrete

Совместимость с браузерами

BCD tables only load in the browser

Смотрите также

Found a content problem with this page?

This page was last modified on 10 окт. 2022 г. 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.

Источник

box-sizing

Применяется для изменения алгоритма расчета ширины и высоты элемента.

Согласно спецификации CSS ширина блока складывается из ширины контента ( width ), значений отступов ( margin ), полей ( padding ) и границ ( border ). Аналогично обстоит и с высотой блока. Свойство box-sizing позволяет изменить этот алгоритм, чтобы свойства width и height задавали размеры не контента, а размеры блока.

Синтаксис

box-sizing: content-box | border-box | padding-box | inherit

Значения

content-box Основывается на стандартах CSS, при этом свойства width и height задают ширину и высоту контента и не включают в себя значения отступов, полей и границ. border-box Свойства width и height включают в себя значения полей и границ, но не отступов ( margin ). Эта модель используется браузером Internet Exporer в режиме несовместимости. padding-box Свойства width и height включают в себя значения полей, но не отступов ( margin ) и границ ( border ). inherit Наследует значение родителя.

HTML5 CSS3 IE Cr Op Sa Fx

В данном примере ширина первого слоя будет равна 324 пиксела, поскольку она складывается из значения ширины контента ( width ), полей слева и справа ( padding ) и толщины границ ( border ). Ширина второго слоя равняется 300 пикселов за счет применения свойства box-sizing . Результат примера в браузере Opera показан на рис. 1.

Ширина блоков

Браузеры

Firefox поддерживает нестандартное свойство -moz-box-sizing .

Safari до версии 5.0, Chrome до версии 10.0, Android до версии 4.0 и iOS Safari до версии 5.0 поддерживают нестандартное свойство -webkit-box-sizing .

Internet Explorer, Chrome, Opera и Safari не поддерживают значение padding-box .

Источник

Two(2) ways to prevent padding from causing an overflow in CSS

When padding is added to an element with a width or a height of 100% it causes that element to overflow. It’s no surprise since padding creates extra space within an element. To fix this issue caused by padding, in this tutorial I am going to introduce two(2) ways of tackling this.

Introduction

1. Using CSS Box-sizing property

Using box-sizing is the best way of tackling the issue of an overflow caused by padding.
The box-sizing property will allow us to define how the width and height of an element are calculated. The default value of the box-sizing property is content-box , but when we set it to border-box this will make the element’s padding and border to also be included in its width and height.
Meaning if we set the element as a width/height of 10px and add padding or a border of 2px , the element’s actual width/height will still be 10px except the padding + border is greater than 10px

.div width: 10px; height: 10px padding: 2px; border: 2px; > 

Element’s actual width = width + padding + border
Element’s actual width = 10px + 4px + 4px = 18px

This is the same for the height.
Element’s actual height = 10px + 4px + 4px = 18px

We used 4px instead of 2px for the border and padding because in our code we are adding 2px to both the left and right sides of the element.

But with the box-sizing property:

.div width: 10px; padding-right: 5px; border-right: 5px; box-sizing: border-box; > 

Element’s actual width = 10px + 5px + 5px = 10px
Element’s actual height = 10px + 4px + 4px = 10px

2. Using the CSS calc() function

The calc() function allows us to perform calculations when we want to specify a property value. The cool thing about the calc() function is that even when the values are in a different unit, it can still be used to calculate the adding(+), subtraction(-), multiplication(*) and division of the values.
For example, we can use the calc() function to do something like this:

For the overflow issue of adding padding to a 100% width/height element Using the calc() function is not the most efficient way of going about it but it will still suffice.

Here is how we go about using the calc() function to handle the overflow issue:

.div width: calc(100% - 20px - 20px ) height: calc(100% - 20px - 20px ) padding: 10px border: 10px > 

Conclusion

In this article, we have learned how to use the box-sizing property and calc() function in CSS to prevent padding from causing an overflow. If you know of any other ways of doing this, feel free to drop it in the commend section below.

Источник

How do I prevent the padding property from changing width or height in CSS?

I am creating a site with DIV s. Everything’s working out except when I create a DIV. I create them like this (example):

When I add the padding-left property, the width of the DIV changes to 220px, and I want it to remain at 200px. Let’s say I create another DIV named anotherdiv exactly the same as newdiv , and put it inside of newdiv but newdiv has no padding and anotherdiv has padding-left: 20px . I get the same thing, newdiv ‘s width will be 220px. How can I fix this problem?

9 Answers 9

-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */ -moz-box-sizing: border-box; /* Firefox, other Gecko */ box-sizing: border-box; /* Opera/IE 8+ */ 

Note: This won’t work in Internet Explorer below version 8.

This is pure magic! — It fixes the box model we all know and hate! i.e. makes it work the way intuition suggests it should — rather than the specs — but as far as I know doesn’t break any specs either 😀 This article clarifies it well. stackoverflow.com/questions/779434/…

Whoops yeah, copy and paste cock up. This is the link I meant to share. paulirish.com/2012/box-sizing-border-box-ftw

Put a div in your newdiv with width: auto and margin-left: 20px

Remove the padding from newdiv.

If you would like to indent text within a div without changing the size of the div use the CSS text-indent instead of padding-left .

This is the only solution that I found worked for my fixed width div. box-sizing did not stop the padding from impacting the width unfortunately, so thanks a tonne for pointing out this awesome little property.

simply add box-sizing: border-box;

A lot of the answers above are correct, but provided little explanation, so i decided to add this for anyone that might need it.

By default, every element box-sizing parameter is set to content-box . Which means, that if you set an element width to 200px and then add a padding of 20px on both horizontal end, this would result to a total width of 240px for that element.

to fix this, you simply need to update the box-sizing parameter and set this to border-box in your css. Or you can do this for all elements by simply adding the following.

This tells the browser to account for any border and padding in the values you specify for an element’s width and height.

So for an element set to border-box with a width of 200px, and a padding of 20px on both sides, it’s total width would still remain 200px (160px as content box and 40px as padding).

Источник

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