skip to Main Content

I want align items with equal spacing and with different parents and without adding any width to those items. I tried below code but not working. Please help me to on this.

<div class="container">
  <div class="buttons">
   <button>test</button>
   <button>test</button>
   <button>test</button>
   <button>test</button>
 </div>
 <button class="outer">test</button>
</div>

.container{
  display:flex;
  width:100%
}
.buttons{
  display: flex;
  width: 75%;
  justify-content: space-between;
}
.outer{
  margin-left:auto
}

Link for my code https://jsfiddle.net/f74ayxh9/

I want result like this with equal spacing and margin but with my HTML structure.
enter image description here

Thank you

2

Answers


  1. You can do this with display: contents on the button container element.

    .container {
      display: flex;
      justify-content: space-between;
      outline: 1px solid red;
      margin: 2em;
    }
    
    .buttons {
      display: contents;
    }
    <div class="container">
    
      <div class="buttons">
        <button>
     test
     </button>
        <button>
     test
     </button>
        <button>
     test
     </button>
        <button>
     test
     </button>
      </div>
      <button class="outer">
    test
    </button>
    </div>
    Login or Signup to reply.
  2.  <style>
        .container {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 10px;
            width: 100%;
        }
    
        .buttons {
            grid-column: 1 / span 4;
            display: contents;
        }
    
        button {
            padding: 10px;
            background-color: #f0f0f0;
            border: 1px solid #ccc;
            cursor: pointer;
        }
    
        .outer {
            grid-column: 5;
        }
    </style>
    

    This solution uses CSS Grid for the main layout and takes advantage of the display: contents property. Here’s a breakdown of the changes:

    We use display: grid on the container instead of display: flex.
    We set up a 5-column grid using grid-template-columns: repeat(5, 1fr).
    The .buttons div uses display: contents, which makes its children behave as if they were direct children of the container.
    Each button (including the outer one) occupies one column of the grid.
    The outer button is placed in the last column using grid-column: 5.

    This approach allows all buttons to be spaced equally without setting explicit widths on the buttons themselves. The gap between the buttons can be adjusted using the gap property on the container.
    If you need to support older browsers that don’t have display: contents, you could use a fallback approach with flexbox, but it would require setting widths on the buttons. Let me know if you need a fallback solution or if you have any questions about this implementation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search