Extra margin appearing on elements with display input-block. How to resolve?

Asked

Viewed 257 times

2

I have a problem with my css. I was working on a style to format some buttons. Everything went well. However, my buttons are with an extra margin showing up. That is, I have not set margin on my buttons, but they are showing in margin.

Example:

.container .item{
    background-color: lightgreen;
    display:inline-block;
    margin:0;
    padding:10px;
}
<div class="container">

  <button class="item">Item</button>
  <button class="item">Item</button>
  <button class="item">Item</button>
</div>

Notice that I set the button to have margin:0, but the same is on the margin.

I realized that the problem happens because of inline-block, because when I change to block with float:left the problem is solved. See:

.container .item {
   float: left;
   background-color: lightgreen;
   margin:0;
   display:block;
}
<div class="container">

      <button class="item">Item</button>
      <button class="item">Item</button>
      <button class="item">Item</button>
    </div>

However float:left in that case it is not desirable as, for example, I usually use text-align:right to change the button alignments, and this does not work with float:left.

Is there any way to remove these extra margins that are appearing without taking the inline-block of my buttons?

2 answers

2

He places these spaces to separate the elements that "are on the same line", such as the spaces that we put between a word and another. It’s "standard" that.

To solve you can:

1) Negativate the margin-left or margin-right of each element (example);

2) Leave the elements side by side in the code HTML, no line break or space (example).

There are even other ways to get around these situations, but I believe that with these two alternatives will already solve your problem.

  • I did not understand why they gave -1. The answer is not wrong.

0

Leave their <div class="container"> with display: flex; or display: table; solves, but I don’t know if it will disturb you in your button alignment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.