'How to align content by using grid css
I want to align to use grid in my css to align a button and other element in the my page web.
I want to line up three side by side headings then the button at the bottom space from three headings at the top by 8 px and center the button. Then leave a margin between the button and the two divs containing the bottom messges as described in this image.
But I can't do it with this code. I want to use the css technique of grids with the titles in column grids and the buttons and the two message divs in line grids
.grid-container {
display: grid;
}
<div>
<div>
<h4>Title 1</h4>
<h4>Title 2</h4>
<h4>Title 3</h4>
</div>
<div class="grid-container">
<button>List of messages</button>
<div class="grid-item item">Message 1</div>
<div class="grid-item item">Message 2</div>
</div>
</div>
Solution 1:[1]
Edit: as requested I moved the tiles to a separate div. Both containers follow a 3 column layout.
To create 3 equally sized columns you can use repeat(3, 1fr) as value for the grid-template-columns property. The syntax is for repeat is:
amount, width/size
1fr (1 fraction) will give every column the same width while it equally distribute all available space to every single fraction. Means with 3 total fractions every fraction has to be 1/3 of the available space.
To align the button in the center column you can use grid-column: 2 / 3; which will start at grid-column-line 2 (between 1st and 2nd column) and end at grid-column-line 3 (between 2nd and 3rd column).
Then to add the margin to the button you simply add the margin to the button directly. I removed the default margin from the tile with h4 { margin: 0; }.
To have the text span the entire width available I used grid-column: 1 / -1; which will start at the first column and end after the last. You should not use span 3 as value as the content needs to specifically start at the first line and not after the button.
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
.grid-container > h4 {
margin: 0;
}
.grid-container > .grid-item > button {
margin: 8px 0 16px 0;
width: min-content;
white-space: nowrap;
}
.center {
text-align: center;
}
.grid-container > .grid-item {
grid-column: 1 / -1;
}
<div class="grid-container">
<h4>Title 1</h4>
<h4>Title 2</h4>
<h4>Title 3</h4>
</div>
<div class="grid-container">
<div class="grid-item center"><button>List of messages</button></div>
<div class="grid-item item">Message 1</div>
<div class="grid-item item">Message 2</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | marc_s |

