cssbox-sizing

Am I correct that I do not need to use box-sizing to create fixed width element as long as padding property is not used


Am I correct that if I have specified width of an HTML element (eg a button) to keep the width fixed then I do not need to specify box-sizing as long as I have used only padding-top and padding-bottom properties? I want to create fixed-width buttons. I found that following two approaches gives the same result. I am new to css. I want to be sure that I have understood the concept correctly and am not missing any corner cases.

approach 1: create a fixed width button. Not using sizing with padding-top and padding-bottom properties.

.button-common-styles-normal{
    background: radial-gradient(ellipse,#268ff4 5%,#4da3f8 95%); 
    border:none;
    color:white;
    border-radius: 8px;
    width:200px;
    text-align: center;
    padding-top: 10px;
    padding-bottom: 10px;

}

approach 2: create a fixed width button. Use box-sizing with padding property

.button-common-styles-normal{
    background: radial-gradient(ellipse,#268ff4 5%,#4da3f8 95%); 
    border:none;
    color:white;
    border-radius: 8px;
    width:200px;
    box-sizing: border-box;
    text-align: center;
    padding: 10px;  
}

Solution

  • In your case both are right, but when you put padding from left and right or put some border it will increase your button width or height when using box-sizing property with default value content-box. I mean it will exceed your width or height which you are defined when using box-sizing property with default value content-box.

    Check out this link, you will be clear https://css-tricks.com/box-sizing/