Search code examples
htmlcsspaddingmargin

Why does changing the margin and padding by a value of one shift all of my buttons?


I was just learning some HTML and CSS and was given an exercise which requires me to make three buttons that expand vertically on hover. In my version of the code, hovering over one button shifts the other buttons over. However, in the instructor's code, his margin-left margin-right padding-left padding-right values differ by 1px, and his buttons do not shift at all. I was considering creating a container but he did it without one and I was wondering how exactly does 1px make that big of a difference?

My code:

            .margin-and-padding {
                padding-top: 9px;
                padding-bottom: 9px;
                padding-right: 16px;
                padding-left: 16px;
        
                margin-right: 11px;
                margin-left: 11px;
                
                border: none;
                background-color: green;
                color: white;
                cursor: pointer;
                font-size: 15px;
                transition: margin 0.2s, padding 0.2s;
            }
        
            .margin-and-padding:hover {
                padding-left: 25px;
                padding-right: 25px;
                margin-right: 0px;
                margin-left: 0px;
            }
 <button class="margin-and-padding">One</button>
        <button class="margin-and-padding">Two</button>
        <button class="margin-and-padding">Three</button>

His code:

        .stretch-button {
          background-color: green;
          color: white;
          border: none;
          font-size: 18px;
          padding-top: 8px;
          padding-bottom: 8px;
          cursor: pointer;
      
          padding-left: 15px;
          padding-right: 15px;
          margin-left: 10px;
          margin-right: 10px;
      
          transition: padding 0.15s,
            margin 0.15s;
        }
      
        .stretch-button:hover {
          padding-left: 25px;
          padding-right: 25px;
          margin-left: 0px;
          margin-right: 0px;
        }
<button class="stretch-button">
        One
      </button>
      <button class="stretch-button">
        Two
      </button>
      <button class="stretch-button">
        Three
      </button>

Could anyone try this out and let me know? Also sorry for any formatting issues, this is my first time posting.


Solution

  • If we take just padding-left in both examples, in your example padding-left: 16px; + margin-left: 11px; = 27px and on hover becomes padding-left: 25px; + margin-left: 0px; = 25px, which will make them shift 2px