2

I have div block with property flex CSS.

This block has 80% width and 50% height of display.

How to display this block in center by horizontal and vertical?

POV
  • 11,293
  • 34
  • 107
  • 201

1 Answers1

4

Flex alignment properties apply to the children of a flex container.

So if you have a div with display: flex, and you want to center this div, you make the parent a flex container. Then you can apply flex alignment properties to the div.

div {
  display: flex;
  width: 80%;
  height: 50vh;
  border: 1px solid black;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
}
<div></div>

Here's a more complete explanation: https://stackoverflow.com/a/33049198/3597276

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • 2
    Why add an answer if a similar question was already answered earlier and you've even linked it? This should be closed as a duplicate. – Marko Gresak Jul 21 '17 at 21:31
  • The only difference is that the flex wrapper is body instead of a wrapping div. This really doesn't deserve a separate question/answer. – Marko Gresak Jul 21 '17 at 21:43
  • I didn't mark as a duplicate because most of those posts deal with centering flex items. This particular question asked about centering a flex container. I felt a more clear explanation would be useful to the OP. – Michael Benjamin Jul 24 '17 at 09:26
  • So, it works only when to set `flex` to body – POV Jul 24 '17 at 17:09
  • Flex layout works only between parent and child. If you want to center an element using flex properties, make the parent a flex container. – Michael Benjamin Jul 24 '17 at 17:11