简体   繁体   English

如何水平居中弯曲<div> ?

[英]How to horizontally center flex <div>?

So what is the proper/correct way to horizontally center the flex <div> ?那么水平居中 flex <div>的正确/正确方法是什么?

 #container { width: 100%; min-height: 100%; }
 <div id="container"> <div className="horizontal-centered">Center this</div> </div>

First change the className to class.首先将 className 更改为 class。 Apply justify-content: center;应用justify-content: center; to .horizontal-centered以. .horizontal-centered

<div id="container">
  <div class="horizontal-centered">...</div>
</div>

#container .horizontal-centered {
  flex-wrap: wrap;
  display: flex;
  flex-direction: row;
  margin: 0;
  justify-content: center;
}

Center align the text in your container:将容器中的文本居中对齐:

#container {
  width: 100%;
  min-height: 100%;
  text-align: center;
}

Then ensure your horizontal margins are set to auto, and the container text is realigned properly.然后确保您的水平边距设置为自动,并正确重新对齐容器文本。

#container .horizontal-centered {
  flex-wrap: wrap;
  display: flex;
  flex-direction: row;
  margin: 0 auto;
  text-align: left;
}

Try this试试这个

 #container { width: 100%; min-height: 100%; padding: 0; margin: 0; display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; align-items: center; justify-content: center; }
 <div id="container"> <div className="horizontal-centered">Center this</div> </div>

Assuming a few things : 1) "className" is a typo and should be class?假设一些事情:1)“className”是一个错字,应该是类? 2) The '.horizontal-centered' is the item needed to be centered, and isn't the flexbox itself. 2) '.horizo​​ntal-centric' 是需要居中的项目,而不是 flexbox 本身。

The flexbox changes needed here are entirely in the container.此处所需的 flexbox 更改完全在容器中。 It assumes the immediate child to be the flex items.它假定直接子项是弹性项目。 Changes shown below.变化如下所示。

 #container { width: 100%; min-height: 100%; background-color:black; height:200px; display:flex; justify-content:center; } #container .horizontal-centered { height:50px; width:50px; background-color: #333; }
 <div id="container"> <div class="horizontal-centered">...</div> </div>

To horizontally center the outermost block, such as a div or article, use the following CSS either in a class or style attribute, either on the body or on a surrounding div:要将最外层块(例如 div 或文章)水平居中,请在 class 或 style 属性中使用以下 CSS,无论是在主体上还是在周围的 div 上:

display: flex;显示:弹性; justify-content: center;对齐内容:居中;

So simple.如此简单。

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

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