Front-end · Júnior

CSS sem medo: box model, flexbox e grid

CSS assusta no começo porque parece imprevisível: você muda uma propriedade e a página inteira se mexe. A boa notícia é que quase toda essa "mágica" se resume a três ideias — o box model, o flexbox e o grid. Entendendo elas, o CSS deixa de ser tentativa e erro e vira algo que você controla.

Tudo é uma caixa: o box model

Todo elemento na tela é uma caixa retangular composta por quatro camadas, de dentro para fora: content (o conteúdo), padding (espaço interno), border (borda) e margin (espaço externo). Pense numa moldura de quadro: a foto é o content, o paspartur é o padding, a moldura é a border e o espaço até o próximo quadro na parede é a margin.

.card {
  width: 200px;
  padding: 20px;
  border: 2px solid;
}
/* Largura real = 200 + 20*2 + 2*2 = 244px (!) */

box-sizing: border-box salva sua sanidade

Por padrão, width conta só o content — padding e border somam por cima, e a caixa estoura. Com box-sizing: border-box, a largura passa a incluir padding e border. É tão essencial que quase todo projeto aplica isso globalmente.

* { box-sizing: border-box; }
.card { width: 200px; padding: 20px; }
/* Agora a largura real É 200px */

display: como a caixa se comporta

O display define o fluxo: block ocupa a linha inteira (como um parágrafo), inline fica na mesma linha (como um <span>) e ignora width/height, e flex/grid transformam o elemento num container que organiza seus filhos.

Flexbox: layout em uma dimensão

Flexbox organiza itens ao longo de um eixo por vez. Você define o eixo principal com flex-direction (linha ou coluna) e o eixo cruzado é o perpendicular. justify-content alinha no eixo principal; align-items alinha no cruzado. Perfeito para barras de navegação, listas de botões, qualquer fileira.

.barra {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

Grid: layout em duas dimensões

Quando você precisa de linhas e colunas ao mesmo tempo — uma galeria, um dashboard, o layout da página inteira — Grid resolve rápido. Você desenha a grade e encaixa os itens.

.galeria {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

Flex ou Grid? E como centralizar

A regra prática: uma direção, use flex; duas direções, use grid. Não é dogma — muita gente faz layout inteiro com flex —, mas é o ponto de partida certo.

CritérioFlexboxGrid
Dimensões1D (linha OU coluna)2D (linhas E colunas)
Melhor paraComponentes, barrasLayout de página, grades
Define forma a partir deConteúdoContainer

E o eterno "como centralizo um elemento?". Com flex, três linhas:

.centro {
  display: flex;
  justify-content: center; /* horizontal */
  align-items: center;     /* vertical */
}
Centralizar virou trivial: o difícil não é mais "como", é lembrar que justify-content e align-items mudam de eixo conforme o flex-direction.

É comum em entrevista pedir exatamente para explicar o box model, a diferença entre content-box e border-box, ou como centralizar vertical e horizontalmente. No dia a dia, é o que você usa em todo componente que monta.

Conclusão

O box model explica o tamanho das coisas, o flexbox organiza em uma dimensão e o grid em duas. Com border-box ligado e essas duas ferramentas no cinto, o CSS deixa de ser sorte. O próximo passo é dar vida à página com JavaScript.

CSS is scary at first because it seems unpredictable: you change one property and the whole page moves. The good news is that almost all of this "magic" boils down to three ideas — the box model, flexbox and grid. Once you understand them, CSS stops being trial and error and becomes something you control.

Everything is a box: the box model

Every element on screen is a rectangular box made of four layers, from the inside out: content, padding (inner space), border and margin (outer space). Think of a picture frame: the photo is the content, the mat is the padding, the frame is the border and the space up to the next picture on the wall is the margin.

.card {
  width: 200px;
  padding: 20px;
  border: 2px solid;
}
/* Actual width = 200 + 20*2 + 2*2 = 244px (!) */

box-sizing: border-box saves your sanity

By default, width counts only the content — padding and border add on top, and the box overflows. With box-sizing: border-box, the width includes padding and border. It's so essential that almost every project applies it globally.

* { box-sizing: border-box; }
.card { width: 200px; padding: 20px; }
/* Now the actual width IS 200px */

display: how the box behaves

display defines the flow: block takes the whole line (like a paragraph), inline stays on the same line (like a <span>) and ignores width/height, and flex/grid turn the element into a container that arranges its children.

Flexbox: one-dimensional layout

Flexbox arranges items along one axis at a time. You define the main axis with flex-direction (row or column) and the cross axis is the perpendicular one. justify-content aligns on the main axis; align-items aligns on the cross axis. Perfect for navigation bars, button lists, any row.

.barra {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

Grid: two-dimensional layout

When you need rows and columns at the same time — a gallery, a dashboard, the whole page layout — Grid solves it quickly. You draw the grid and place the items in it.

.galeria {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

Flex or Grid? And how to center

The practical rule: one direction, use flex; two directions, use grid. It's not dogma — plenty of people build entire layouts with flex —, but it's the right starting point.

CriterionFlexboxGrid
Dimensions1D (row OR column)2D (rows AND columns)
Best forComponents, barsPage layout, grids
Shape defined fromContentContainer

And the eternal "how do I center an element?". With flex, three lines:

.centro {
  display: flex;
  justify-content: center; /* horizontal */
  align-items: center;     /* vertical */
}
Centering became trivial: the hard part is no longer "how", it's remembering that justify-content and align-items switch axes depending on flex-direction.

Interviews commonly ask you to explain the box model, the difference between content-box and border-box, or how to center vertically and horizontally. Day to day, it's what you use in every component you build.

Conclusion

The box model explains the size of things, flexbox arranges in one dimension and grid in two. With border-box turned on and these two tools in your belt, CSS stops being luck. The next step is bringing the page to life with JavaScript.

Leia também

Voltar à trilha