1

I just want to make my button expands full width to its container with some margin to itself, but it's not working. I have tried box-sizing: border-box, but as you can see in the snippet, still no luck because notice the right-side of the button, it's like overshoot..

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    * {
      box-sizing: border-box;
    }
    
    .cont {
      width: 100vw;
      background-color: white;
    }
    
    .block {
      margin: 10px;
      display: block;
      width: 100%;
      background-color: #4CAF50;
      color: white;
      padding: 10px;
    }
  </style>
</head>
<body>
  <div class="cont">
    <button class="block">Block Button</button>
  </div>
</body>
</html>
kyw
  • 6,685
  • 8
  • 47
  • 59

3 Answers3

2

That is because when the width is already 100%. Adding 10px margin to the left will cause it to be 100% + 10px, therefore overshoots the width of the container. Alternatively, you can add 10px padding to the container instead.

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    * {
      box-sizing: border-box;
    }
    
    .cont {
      width: 100vw;
      background-color: white;
      padding: 10px; /*Added Padding*/
    }
    
    .block {
      /*margin: 10px;*/
      display: block;
      width: 100%;
      background-color: #4CAF50;
      color: white;
      padding: 10px;
    }
  </style>
</head>

<body>

  <div class="cont">
    <button class="block">Block Button</button>
  </div>

</body>

</html>
joohong89
  • 1,241
  • 8
  • 15
  • You can also remove the margin on the body to remove the scrollbar in this snippet - maybe OP is also seeing that. – JasonB Jun 04 '19 at 02:11
  • 1
    Oh nice. I thought the button's `width:100%` would have taken the `margin` into account and shrink accordingly..Ok thanks! – kyw Jun 04 '19 at 02:15
0

Please remove the following commented CSS and it will work absolutely fine,

  * {
        box-sizing: border-box;
    }
    .cont {
        /* width: 100vw; */
        background-color: white;
        width: 100%;
    }
    .block {
        /* margin: 10px; */
        display: block;
        width: 100%;
        background-color: #4CAF50;
        color: white;
        padding: 10px;
    }
0

please try this.

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>   
    .block {
      /*margin: 10px;*/
      display: block;
      width: 100%;
      background-color: #4CAF50;
      color: white;
      padding: 10px;
    }
  </style>
</head>

<body>
  <div class="cont">
    <button class="block">Block Button</button>
  </div>

</body>

</html>