0

When I use margin: 10px with width: 100% it gives me the button more bigger that the screen, and the only solution is removing the margin but I need it. This is a simple demo to demonstrate my problem. This is breaking my look and feel of my app.

You can see in this link https://www.w3schools.com/code/tryit.asp?filename=G7HZARR1F6M7 what I am trying to do and the weird behavior that I receive.

.button {
  background-color: #4CAF50;
  /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  width: 100%;
}

.without-margin {
  margin: 0px;
}

.with-margin {
  margin: 10px;
}
<div>
  <button class="button without-margin">What I want but adding margin</button>
  <button class="button with-margin">What I receive putting some margin</button>
</div>
Joao Pixeles
  • 142
  • 8

2 Answers2

1

Because the total "width" is being 100% + 20px (10px each side).
One way to fix it is using calc() for width:

.button {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    width: calc(100% - 20px); /* 100% subtracting horizontal margin */
}
Azametzin
  • 5,223
  • 12
  • 28
  • 46
0

Try using padding instead, the below code will give your desired output.

.with-margin {
    margin-top: 10px;
    padding-left: 10px;
    padding-right: 10px;
}
j9070749
  • 815
  • 2
  • 11
  • 22