1

Why are divs inside a grid layout not aligned by default?

How can I align them?

.dpNav{
width:50%;
display:grid;
grid-template-columns: repeat(5, 1fr);
text-align:center;
background:gold;
}
<div class='dpNav' id='dpNav'>
<div class='yearTitle' id='yearTitle'>2019</div>
<div class='btnYear' id='btnYear'>&#x267B;</div>
<div></div>
<div class='monthTitle' id='monthTitle'>JAN</div>
<div class='btnMonth' id='btnMonth'>&#x267B;</div>
</div>
TylerH
  • 20,799
  • 66
  • 75
  • 101
qadenza
  • 9,025
  • 18
  • 73
  • 126

3 Answers3

2

Adding in align-items:center on the parent container will achieve what you are looking for. The reason why it isn't set by default is to give the user control of its placement. CSS-Tricks has a really in-depth breakdown of the different ways you can align items in a grid.

.dpNav{
width:50%;
display:grid;
align-items:center;
grid-template-columns: repeat(5, 1fr);
text-align:center;
background:gold;
}
<div class='dpNav' id='dpNav'>
<div class='yearTitle' id='yearTitle'>2019</div>
<div class='btnYear' id='btnYear'>&#x267B;</div>
<div></div>
<div class='monthTitle' id='monthTitle'>JAN</div>
<div class='btnMonth' id='btnMonth'>&#x267B;</div>
</div>
Jbsmooth
  • 43
  • 6
1

add align-items:center;

.dpNav{
width:50%;
display:grid;
grid-template-columns: repeat(5, 1fr);
text-align:center;
background:gold;
align-items:center;
}
<div class='dpNav' id='dpNav'>
<div class='yearTitle' id='yearTitle'>2019</div>
<div class='btnYear' id='btnYear'>&#x267B;</div>
<div></div>
<div class='monthTitle' id='monthTitle'>JAN</div>
<div class='btnMonth' id='btnMonth'>&#x267B;</div>
</div>
doğukan
  • 23,073
  • 13
  • 57
  • 69
1

.dpNav{
width:50%;
display:grid;
grid-template-columns: repeat(5, 1fr);
text-align:center;
vertical-align: middle;
background:gold;
padding-bottom: 2px
}

.text {
 padding-top: 3px;
 }
<div class='dpNav' id='dpNav'>
<div class='yearTitle text' id='yearTitle'>2019</div>
<div class='btnYear' id='btnYear'>&#x267B;</div>
<div></div>
<div class='monthTitle text' id='monthTitle'>JAN</div>
<div class='btnMonth' id='btnMonth'>&#x267B;</div>
</div>

if you don't like my tweaks to the padding, you could also put the contents inside a span and set the CSS for that to vertical-align: middle.

Yvonne Aburrow
  • 2,602
  • 1
  • 17
  • 47
  • And could someone explain - why `Dogukan's` solution is not perfect - why I need additional `padding` and `spans` - why the divs are not aligned by default? – qadenza Jan 02 '19 at 21:23
  • it seems the default setting is for the text to be aligned to the bottom rather than the center. The recycle icons are a slightly different height to the text. – Yvonne Aburrow Jan 03 '19 at 16:17