I was trying to create a basic tic tac toe game with React (but this question is just about CSS).
Initially, I wrote the following code for the grids:
App.js:
import React, { Component } from 'react';
import Square from './Square';
class App extends Component {
render() {
return (
<div>
<div><Square /><Square /><Square /></div>
<div><Square /><Square /><Square /></div>
<div><Square /><Square /><Square /></div>
</div>
)
}
}
export default App;
where each Square is just an empty div (so I'll omit the Square.js code here), which has the following style:
{
backgroundColor: "white",
border: "black solid 2px",
textAlign: "center",
fontSize: "20px",
width: "40px",
height: "40px",
margin: -1,
display: "inline-block",
}
What happened was the Squares jumped up and down when rendering "X", "O" and the empty string like so:
Then I consulted React's official tutorial's code, where they did it differently in 2 ways:
In Square's CSS, the added "float: left" instead of my "display: inline-block"
They added another class "board-row" for each row, i.e. for each of the the div that wraps around the 3 Squares, with the following CSS:
.board-row:after{ clear: both; content: ""; display: block; }
My question is:
Why wasn't my code working?
Why is the new code working?
I do have some initial thoughts: The new code has the squares of each row to float left, then it creates an empty element with "clear: both", which moves the empty element below the floated squares, forcing the next row of Squares to go below. (without "clear: both" all 9 squares will be on the same row). "display: block" also gives the empty element the ability to push the squares around.
Does it make sense? I also have trouble explaining what's the problem with the original code.
Normally I wouldn't care as long as the code is already working, but I'm trying to teach someone else React, so I want to be able to explain to them.