Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 2, 2019 11:16 pm GMT

Meet border-box, my best friend.

Have you been given the advice to use box-sizing: border-box; but not completely understand what it was doing for you?

Whether working to recreate comps down to the pixel or building my own designs, border-box has made my life a lot easier. But it didn't seem any easier until I understood what it was doing for me. That's why it is my best friend and I think you might want it in your life, too!

Before you dive into this, you should have an understanding of content, padding, border, and margin and the role each of those play in the box model.

box-sizing: content-box;

content-box is the default value for the box-sizing property for most elements. The content in content-box means that content, and only content, will use the height and width that are applied to an element.

If we apply a width of 200px to a div, we won't be surprised to see it take up 200px. Now, when we add on 10px of padding and a 3px border, we will see that the box is now 226px wide:

If I truly only have 200px for this element, I now need to subtract the padding and border from the content, so I set the content at 174px. Any tiny change I decide to make to the padding or border from there on out, I'll also have to calculate and make a change to the content.

box-sizing: border-box;

The border in border-box means that the border and everything inside of it, padding and content, will count toward the defined height and width of the element.

If we apply a width of 200px to a div element, then the 10px padding and 3px border, the content, padding and border will all fit within that 200px width:

If I need to modify the border or padding at any time, I can count on border-box to keep the element the size I defined, saving me tome from having to do the math and adjust the content's height and width every time.

Different Elements Different Default Styles

While most elements default to content-box, not all necessarily do! This depends on the user agent stylesheet for the browser you are using. In Chrome's latest stylesheet, buttons are defaulted to border-box along with several types of inputs.

Example

To see this in action, visit this CodePen. Commenting out lines 30 and 34 one at a time can give you a feel for what each declaration does.

Wrap Up

border-box may be your new best friend, but only if you know what it is doing for you. Try adding it to the next small project you whip up and see how it helps you!


Original Link: https://dev.to/ameseee/meet-border-box-my-best-friend-a56

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To