Home > Software engineering >  How to center an item with Flexbox?
How to center an item with Flexbox?

Time:08-30

I would like to center something in my code with flexbox. It works for all other elements, only here something seems to be wrong. Does anyone have an idea?

.answer {
  text-shadow: 0 0 2px gr;
  display: flex;
  justify-content: center;
  border-radius: 5px;
  margin-bottom: 20px;
  padding: 20px;
  border: 5px solid black;
  border-radius: 5px;
  width: 50%;
}
<section >
  <p>Answer</p>
</section>

This is how it gets displayed in my live server

CodePudding user response:

Your "Answer" is centered in the box. Are you trying to center the box on the page? In that case, you would need to apply flex styles to the parent. In this case, the body:

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.answer {
  text-shadow: 0 0 2px gr;
  display: flex;
  justify-content: center;
  border-radius: 5px;
  margin-bottom: 20px;
  padding: 20px;
  border: 5px solid black;
  border-radius: 5px;
  width: 50%;
}
<section >
  <p>Answer</p>
</section>

CodePudding user response:

You can add body tag on css to make center on the page

to make horizontal center

body {
  display: flex,
  justify-content: center
}

or make vertical center

body {
  display: flex,
  align-items: center,
  height: 100vh /* This is for full height of your screen */
}

or make horizontal and vertical center

body {
  display: flex,
  justify-content: center,
  align-items: center,
  height: 100vh
}
  • Related