简体   繁体   English

如何使用 Flexbox 使项目居中?

[英]How to center an item with Flexbox?

I would like to center something in my code with flexbox.我想用 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.在这种情况下,您需要将 flex styles 应用于父级。 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您可以在 css 上添加body标签以使页面居中

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/请参阅 FlexBox 上的本指南,我认为它可以帮助您很多https://css-tricks.com/snippets/css/a-guide-to-flexbox/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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