Explain Codes LogoExplain Codes Logo

How can I make space between two buttons in the same div?

html
responsive-design
css
styling
Nikita BarsukovbyNikita Barsukov·Aug 21, 2024
TLDR

To add space between buttons, you can utilize margins in CSS:

<button style="margin-right: 10px;">Button 1</button> <button>Button 2</button>

Alternatively, use flexbox gap for a modern and elegant solution:

<div style="display: flex; gap: 10px;"> <button>Button 1</button> <button>Button 2</button> <!-- Enjoy the extra breathing space! --> </div>

Using Bootstrap for spacing

In Bootstrap, you can add horizontal margins by using utility classes such as mx-2:

<button class="btn mx-2">Button 1</button> <button class="btn">Button 2</button> <!-- Wait, where's my space? Add Bootstrap class! -->

Be sure to utilize Bootstrap containers like btn-toolbar if you desire space between your buttons:

<div class="btn-toolbar" role="toolbar"> <button class="btn btn-primary mr-2">Button 1</button> <!-- I'm first! --> <button class="btn btn-secondary">Button 2</button> <!-- Always the bridesmaid... --> </div>

Remember, btn-group is a no-no if you want ample space between buttons.

Responsive button spacing

Incorporating a responsive button layout is much simpler with Bootstrap's grid system:

<div class="form-group"> <div class="row"> <div class="col-md-6"> <button class="btn btn-primary w-100">Button 1</button> </div> <div class="col-md-6"> <button class="btn btn-secondary w-100">Button 2</button> <!-- No squishing, please! --> </div> </div> </div>

This way, col-md-6 creates equal space for both buttons, adapting to the device's width.

Using flexbox for custom spacing

Flexbox allows you to control spacing outside of Bootstrap as well:

<div style="display: flex; justify-content: space-around;"> <button>Button 1</button> <button>Button 2</button> <!-- So. Much. Room. For. Activities! --> </div>

Pair this with custom CSS classes for maximum control and maintainable codes:

<style> .btn-space { margin-right: 15px; } /* I need my space! */ </style> <button class="btn-space">Button 1</button> <button>Button 2</button>

Styling buttons in forms

In forms, use form-control along with btn class to align buttons and add proper margins:

<form> <input type="text" class="form-control mb-2"> <button class="btn btn-primary">Submit</button> <!-- Because everyone likes to submit! --> <button class="btn btn-secondary ml-2">Cancel</button> <!-- This button is cool too. --> </form>

Button targeting and alignment

Indentify a button for specific styling or javascript function with an id attribute:

<button id="button1">Button 1</button> <!-- I'm special! -->

Bootstrap prefers utility classes like ml-auto for alignment within flex containers:

<div class="d-flex"> <button class="ml-auto">Button on the right</button> <!-- I'm right always... ain't I? --> </div>