📜 ⬆️ ⬇️

CSS3: Box-Sizing property

Previously, if we made a div with a width and height of 100px, added padding 10px and border 10px, then the square was not 100x100, but 140x140 px:



But sometimes it is required that the div be a fixed width for any values ​​of padding and border. In CSS3, the box-sizing property will help.
')

Use box-sizing


This property has two values:

div { width: 100px; height: 100px; padding: 10px; border: 10px solid #eaeaea; box-sizing: border-box; -moz-box-sizing: border-box; /*Firefox 1-3*/ -webkit-box-sizing: border-box; /* Safari */ } 




Browser Support


The box-sizing property supports most modern browsers: Firefox 3.6+, Safari 3+, Opera 8.5+ and Internet Explorer 8+. Current data can be viewed on the website caniuse.com .

Practical example


Consider a real example of using the box-sizing property. There is a menu of five items:

 <ul> <li><a href="#">Menu 1</a></li> <li><a href="#">Menu 2</a></li> <li><a href="#">Menu 3</a></li> <li><a href="#">Menu 4</a></li> <li><a href="#">Menu 5</a></li> </ul> 


Add a bit of CSS, incl. The fixed menu width is 500 px and the width of each item is 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 { background-color: #D4D4D4; border-right: 0; } 


The menu looks fine:



But when adding a left or right border, the last menu item moves out, because it does not fit:

 nav a { border-left: 1px solid #aaa; border-right: 1px solid #f3f3f3; } 




But if you use box-sizing, then this problem does not exist:

 nav a { border-left: 1px solid #aaa; border-right: 1px solid #f3f3f3; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; } 

demo

Useful reading on the topic


- Box-sizing: border-box - FTW - Paul Irish
- Make it your best

Source: https://habr.com/ru/post/149441/


All Articles