I am creating a calculator layout with CSS Grid, but I want to make sure the columns are evenly distributed across the container, with the same amount of space between each button, similar to how the flexbox property justify-content: space-between works. I want to make sure that the columns themselves have even gaps between them, and the left and right edges of the buttons are aligned with the container's edges.
Here is my HTML structure:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Calculator</title><link rel="stylesheet" href="styles.css"></head><body><div class="calculator"><div class="screen">Screen</div><div class="button-container"><button>AC</button><button>()</button><button>%</button><button>+</button><button>7</button><button>8</button><button>9</button><button>*</button><button>4</button><button>5</button><button>6</button><button>-</button></div></div></body></html>And here’s the CSS I'm using:
/* General reset for margin, padding, and box-sizing */* { margin: 0; padding: 0; box-sizing: border-box;}/* Calculator container */.calculator { border-radius: 1.5rem; min-height: 80vh; max-width: 350px; background-color: #fae4e4; padding: 1rem; margin: 0 auto; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);}/* Calculator screen */.screen { min-height: 100px; border-radius: 1rem 1rem 0 0; background-color: #ded3d3; padding: 1rem; display: flex; align-items: center; justify-content: flex-end; font-size: 2rem;}/* Button container */.button-container { padding-top: 0.5rem; display: grid; grid-template-columns: repeat(4, 1fr); /* 4 equal columns */ justify-content: space-between; /* Attempt to add space between columns */ row-gap: 1rem; /* Space between rows */ text-align: center;}/* Buttons style */.button-container button { border-radius: 50%; height: 3rem; width: 3rem; background-color: #ffcccc; border: none; font-size: 1.5rem; cursor: pointer; transition: background-color 0.3s;}.button-container button:hover { background-color: #ffb3b3;}Problem:
Right now, I have 4 columns set using grid-template-columns: repeat(4, 1fr);, but I need the space between the columns to be even, with no extra space on the left or right edges of the grid. The current justify-content: space-between; doesn't seem to affect the columns in the way I want.
I want the columns to have even space between them, just like flexbox's space-between, while making sure the buttons on the left and right edges are aligned with the container's edges.
What I’ve tried:
- I tried using
justify-content: space-between;in the.button-containerbut it didn’t work as expected with the grid. - I’ve tried adjusting the
gapproperty, but it’s not giving the desired effect.
What I want:
I want the columns of buttons to be evenly spaced within the grid and for the left and right edges to be aligned with the container.