Css border fixed size

CSS box-sizing Property

Include padding and border in the element’s total width and height:

More «Try it Yourself» examples below.

Definition and Usage

The box-sizing property defines how the width and height of an element are calculated: should they include padding and borders, or not.

Default value: content-box
Inherited: no
Animatable: no. Read about animatable
Version: CSS3
JavaScript syntax: object.style.boxSizing=»border-box» Try it

Browser Support

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

Numbers followed by -webkit- or -moz- specify the first version that worked with a prefix.

CSS Syntax

Property Values

Value Description Demo
content-box Default. The width and height properties (and min/max properties) includes only the content. Border and padding are not included Demo ❯
border-box The width and height properties (and min/max properties) includes content, padding and border 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

Specify two bordered boxes side by side:

Example

Set the «universal box-sizing»:

Читайте также:  Статус для бота дискорд python

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.

Источник

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 , , and elements, and for 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

box-sizing: border-box; box-sizing: content-box; /* Global values */ box-sizing: inherit; box-sizing: initial; box-sizing: revert; box-sizing: revert-layer; box-sizing: unset; 

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

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.

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 */ > 

Result

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.

Источник

CSS3: свойство Box-Sizing

Раньше, если мы делали div шириной и высотой 100px, добавляли padding 10px и border 10px, то получался квадрат не 100х100, а 140х140 px:

Но иногда требуется, чтобы div был фиксированной ширины при любых значениях padding и border. В CSS3 нам поможет свойство box-sizing.

Использование box-sizing

  • content-box — по умолчанию, контент внутри div’а будет отображаться по-старому, т.е. как в примере выше: вместо 100х100 будет 140х140
  • border-box позволяет значения padding и border вычитать из ширины и длины блока, т.е. в нашем примере div останется с фиксированными параметрами, но для контента останется 60х60 px

Поддержка браузерами

Свойство box-sizing поддерживает большинство современных браузеров: Firefox 3.6+, Safari 3+, Opera 8.5+ и Internet Explorer 8+. Актуальные данные можно посмотреть на сайте caniuse.com.

Практический пример

Рассмотрим реальный пример использования свойства box-sizing. Есть меню из пяти пунктов:

Добавим немного CSS, в т.ч. фиксированную ширину меню в 500 px и ширину каждого элемента в 100 px:

nav < width: 500px; margin: 50px auto 0; height: 50px; >nav ul < padding: 0; margin: 0; >nav li < float: left; >nav a < display: inline-block; width: 100px; height: 100%; background-color: #ccc; color: #555; text-decoration: none; font-family: Arial, sans-serif; font-size: 12pt; line-height: 300%; text-align: center; >nav a < display: inline-block; width: 100px; height: 100%; color: #555; text-decoration: none; font-family: Arial, sans-serif; >nav li:nth-child(1) a < background-color: #E9E9E9; border-left: 0; >nav li:nth-child(2) a < background-color: #E4E4E4; >nav li:nth-child(3) a < background-color: #DFDFDF; >nav li:nth-child(4) a < background-color: #D9D9D9; >nav li:nth-child(5) a

Но при добавлении левого или правого border’а последний пункт меню съезжает, потому что не помещается:

Но если использовать box-sizing, то этой проблемы нет:

Источник

Box Sizing

The box-sizing property can make building CSS layouts easier and a lot more intuitive. It’s such a boon for developers that here at CSS-Tricks we observe International Box-Sizing Awareness Day in February. But, how is it so helpful and beloved that it deserves its own internet holiday? Time for a little bit of CSS history.

Since the dawn of CSS, the box model has worked like this by default: width + padding + border = actual visible/rendered width of an element’s box height + padding + border = actual visible/rendered height of an element’s box This can be a little counter-intuitive, since the width and height you set for an element both go out the window as soon as you start adding padding and borders to the element. Back in the old days of web design, early versions of Internet Explorer (

Those wishes were granted when the box-sizing property was introduced in CSS3. Though box-sizing has three possible values ( content-box , padding-box , and border-box ), the most popular value is border-box . Today, the current versions of all browsers use the original “width or height + padding + border = actual width or height” box model. With box-sizing: border-box; , we can change the box model to what was once the “quirky” way, where an element’s specified width and height aren’t affected by padding or borders. This has proven so useful in responsive design that it’s found its way into reset styles. At this point you may be asking yourself, “Is it possible that Old IE did something right?” Plenty of people think so.

This demo shows how border-box can help make responsive layouts more manageable. The parent div ‘s width is 50%, and it has 3 children with different widths, padding, and margins. Click the border-box button to get all the children in the right place inside the parent. See the Pen Box Sizing Layout Demo by CSS-Tricks (@css-tricks) on CodePen.

Good, Better, and (Probably) Best box-sizing Reset Methods

This works fairly well, but it leaves out pseudo elements, which can lead to some unexpected results. A revised reset that covers pseudo elements quickly emerged:

This method selected pseudo elements as well, improving the normalizing effect of border-box . But, the * selector makes it difficult for developers to use content-box or padding-box elsewhere in the CSS. Which brings us to the current frontrunner for best practice:

Universal Box Sizing with Inheritance

This reset gives you more flexibility than its predecessors — you can use content-box or padding-box (where supported) at will, without worrying about a universal selector overriding your CSS. We went into more depth on this technique and the reasoning behind it in “Inheriting box-sizing Probably Slightly Better Best Practice”. One potential gripe with it is that box-sizing isn’t normally inherited, so it’s specialized behavior, not quite the same as something you’d normally put in a reset.

Every current browser supports box-sizing: border-box; unprefixed, so the need for vendor prefixes is fading. But, if you need to support older versions of Safari ( -webkit and -moz , like this:

box-sizing: border-box; is supported in the current versions of all major browsers. The less-commonly used padding-box is only supported in Firefox at the moment. There’s more comprehensive information about browser support in our box-sizing almanac entry. There are a few issues with older versions of Internet Explorer (8 and older). IE 8 doesn’t recognize border-box on elements with min/max-width or min/max-height (this used to affect Firefox too, but it was fixed in 2012). IE 7 and below do not recognize box-sizing at all, but there’s a polyfill that can help.

Источник

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