简体   繁体   中英

How to center an item with Flexbox?

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 class="answer"> <p>Answer</p> </section>

This is how it gets displayed in my live server

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 class="answer"> <p>Answer</p> </section>

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
}

 body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0px; /*add to remove body margin which always present and makes v-scroll if not removed*/ }.answer { display: flex; justify-content: center; margin-bottom: 20px; /*Remove it if their is no other content on page*/ padding: 20px; border: 5px solid black; border-radius: 5px; width: 50%; }
 <section class="answer"> <p>Answer</p> </section>

See this guide on FlexBox, I think it can help you a lot https://css-tricks.com/snippets/css/a-guide-to-flexbox/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM