Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 如何在flex容器中居中放置两个flex项目之一?_Html_Css_Flexbox - Fatal编程技术网

Html 如何在flex容器中居中放置两个flex项目之一?

Html 如何在flex容器中居中放置两个flex项目之一?,html,css,flexbox,Html,Css,Flexbox,我希望框2位于#框cntnr的中心,因此我使用align self属性。我愿意接受其他方法来实现这一点 HTML 假设您希望在flex容器中垂直和水平居中放置BOX#2,那么您需要做的第一件事是为容器提供一些高度 在代码中,flex项只能水平居中,因为容器没有指定高度,所以它解析为内容高度,并且垂直空间有限 HTML(无更改) CSS html, body { height: 100%; } body { margin: 0; } #box-cntnr { display: flex;

我希望框2位于
#框cntnr
的中心,因此我使用
align self
属性。我愿意接受其他方法来实现这一点

HTML 假设您希望在flex容器中垂直和水平居中放置BOX#2,那么您需要做的第一件事是为容器提供一些高度

在代码中,flex项只能水平居中,因为容器没有指定高度,所以它解析为内容高度,并且垂直空间有限

HTML(无更改)

CSS

html, body { height: 100%; }

body { margin: 0; }

#box-cntnr {
  display: flex;
  position: relative;
  height: 100%;
  background-color: yellow;
}

.box {
  width: 100px;
  height: 100px;
  background-color: lightblue;
  margin: 10px;
}

#b2 {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

Flex对齐属性,如
对齐内容
对齐项目
对齐自我
自动
页边距,通过在Flex容器中分配可用空间来工作。因此,如果BOX#2是容器中唯一的柔性项,我们可以使用这些属性来实现完美的定心

但是,长方体2有一个同级(长方体1),因此这些属性不能有效地用于居中,因为长方体1占用空间,这将导致计算中断。换句话说,柔性对齐属性将在剩余空间中居中放置方框#2


解决这个问题最简单的方法是使用。我们可以将
position:relative
应用于容器,将
position:absolute
应用于框2。这将从文档流中删除方框#2,并使我们能够在父级的整个空间内自由对齐它。

您可以使用此…并添加 像这样

.box{
宽度:100px;
高度:100px;
背景颜色:浅蓝色;
利润率:10px;
}
#箱式cntnr{
显示器:flex;
}
#b1{
自对准:居中;
}
.ctr1{
保证金:0自动;
显示器:flex;
}

方框1
方框2
.box {
  width: 100px;
  height: 100px;
  background-color: lightblue;
  margin: 10px;
}

#box-cntnr {
  display: flex;
}

#b1 {
  align-self: center;
}
html, body { height: 100%; }

body { margin: 0; }

#box-cntnr {
  display: flex;
  position: relative;
  height: 100%;
  background-color: yellow;
}

.box {
  width: 100px;
  height: 100px;
  background-color: lightblue;
  margin: 10px;
}

#b2 {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}