基于子元素的div中心

时间:2019-12-28 16:36:13

标签: html css twitter-bootstrap bootstrap-4

包装纸中有三个按钮。您可能会在代码段中看到,中间的是中等大小,而左边的是较宽,右边的是最小。我在这个包装器中还有一个标题,该标题居中对齐。

我要实现的目标是根据中号按钮(中号按钮)对齐按钮(在本例中为cheerio div)。我希望该按钮位于标题的中央。

这是我希望按钮对齐的图片:

enter image description here

尽管最好使用纯CSS解决方案,但如果需要,我愿意使用JS。

我该怎么做?

.btns
#content {
  background: black;
  width: 300px;
  height: 150px;
}

#title {
  padding-top: 30px;
  color: white;
  text-align: center;
}

.btns > a {
  text-decoration: none;
  color: blue;
  border: 2px solid red;
}

#b2 {
 margin: auto 15px auto 15px;
}

.btns {
  display: flex;
  justify-content: center;
}

3 个答案:

答案 0 :(得分:1)

第一个问题是为什么您会想要这种行为?

您可以通过多种不同的方式实现这一目标,其中之一就是使用网格。那会起作用,但是从设计的角度来看,除非您的用例确实证明了这一点,否则这并不是一个令人愉悦的模式。

Test pen link

#content {
  background: black;
  width: 300px;
  height: 150px;
}

#title {
  padding-top: 30px;
  color: white;
  text-align: center;
}

.btns{
  display:grid;
  grid-gap: 10px;
  grid-template-columns: 1fr auto 1fr;
}

.btns > a {
  text-decoration: none;
  color: blue;
  border: 2px solid red;
}

.b1{
  text-align: right;
}

希望这可以解决您的问题!

答案 1 :(得分:-1)

您应该为此使用flexbox。

display: flex; 
flex-direction: row; 
justify-context: center; 
align-items:center;

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox

答案 2 :(得分:-2)

如果中间链接应始终位于中间,则可以在其上设置flex: 0 0 auto,在其他2上设置flex: 1 1 0