【问题标题】:Vertically centering, absolute position, multiple elements垂直居中,绝对位置,多个元素
【发布时间】:2017-02-01 12:29:09
【问题描述】:

我正在使用以下方法在高度未知的 div 中垂直居中高度未知的元素。

http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/

我居中的元素是锚标签,所以这个答案解决了位置相对问题。

When to use position absolute vs position relative when vertically aligning with css

但是,由于我有一个元素紧挨着另一个元素,因此在使用 position:absolute 时它们会重叠

有什么办法可以解决这个问题吗? (我不能使用 flexbox)

HTML

<div class"parent-container">
  <a href="">Some content</a>
  <a href=""><img src""></a>
</div>

CSS

.parent-container {
 -webkit-transform-style: preserve-3d;
 -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
}

.parent-container a {
 position: absolute;
 top: 50%;
 transform: translateY(-50%);
}

【问题讨论】:

  • 寻求代码帮助的问题必须包含重现它所需的最短代码在问题本身中最好在Stack Snippet 中。见How to create a Minimal, Complete, and Verifiable example
  • 但显而易见的答案是将两个链接包装在一个 div 中并垂直居中 that
  • 有代码,似乎没必要,因为一切都在链接中,我指出的实际问题不包含代码
  • 不能修改布局怎么办?
  • 如果链接消失,问题就变得毫无用处。这就是为什么我们需要问题中的代码

标签: html css css-position vertical-alignment


【解决方案1】:

使孩子内联块并使用vertical-align:middle。无需定位。

a {
  vertical-align: middle;
  display: inline-block;
}
.parent-container {
  text-align: center;
  background:palegoldenrod
}
<div class="parent-container">
  <a href="">Some content</a>
  <a href="">
    <img src="http://www.fillmurray.com/140/100">
  </a>
</div>

如果包含的父元素比内容高,您可以使用伪元素。

a {
  display: inline-block;
  vertical-align: middle;
}
.parent-container {
  text-align: center;
  height: 150px;
  background: pink;
}
.parent-container::before {
  content: '';
  height: 100%;
  display: inline-block;
  vertical-align: middle;
  margin-right: -0.25em;
  /* Adjusts for spacing */
}
<div class="parent-container">
  <a href="">Some content</a>
  <a href="">
    <img src="http://www.fillmurray.com/140/100">
  </a>
</div>

【讨论】:

  • 我不能有固定的高度。
  • 我不是说你必须这样做。高度是为了表明垂直居中无论高度是 - jsfiddle.net/33obkxh8
  • 虽然您的代码可以正常工作,但我的项目中一定有其他东西阻止了它的工作。无论如何谢谢
猜你喜欢
  • 2012-03-21
  • 2017-07-16
  • 2012-08-22
  • 2013-05-12
  • 2011-03-19
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
  • 2012-01-20
相关资源
最近更新 更多