Marwane
Marwane

Reputation: 3

how do i center text horizontally with grid

i am learning css right now and after finishing my grid lessons i have to solve the assignments but i have some problems here... look at the code and compare it with the photo

<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
</div>

*{
box-sizing: border-box;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.grid {
background-color: #ddd;
padding: 20px;
width: 800px;
height: 400px;
text-align: center;
margin: auto;
display: grid;
grid-template-columns: auto 1fr 1fr auto;
grid-template-rows: 1fr auto;
gap: 20px 20px;
}
.grid div{
background: #403f3f;
color: white;
}

click me to open the photo

Upvotes: 0

Views: 228

Answers (2)

.grid div{
    display:flex;
    /* for start flex */
    align-items: center;
    /* for rows center */
    justify-content: center;
    /* for columns center */
}
or
.grid div{
    display:grid;
    /* for start grid */
    place-content: center;
    /* rows and columns center */
}

Upvotes: 0

Brady Agranoff
Brady Agranoff

Reputation: 120

First things first, Make sure your css is either on a different file being imported, or inside a tag.

Other than that, the adjustment for the text is pretty simple. I would make each div a flex box, and align items center, as well as justify content center as so:

*{
box-sizing: border-box;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.grid {
background-color: #ddd;
padding: 20px;
width: 800px;
height: 400px;
text-align: center;
margin: auto;
display: grid;
grid-template-columns: auto 1fr 1fr auto;
grid-template-rows: 1fr auto;
gap: 20px 20px;
}
.grid div{
background: #403f3f;
color: white;
display: flex;
justify-content: center;
align-items: center
}

That simple fix should vertically and horizontally center it!!

Best of luck.

Upvotes: 1

Related Questions