【问题标题】:How to do vertical center while height is auto?高度为自动时如何做垂直居中?
【发布时间】:2015-01-09 10:32:17
【问题描述】:

我遇到了一些 CSS 的小问题。

我的 Container 的宽度是静态的,但高度是灵活的。现在我想将我的容器垂直居中,但我不知道如何。

你能帮帮我吗?

section article {
        position: absolute;
        width: 350px;
        height: auto;
        right: 10%;
        z-index: 2;
        background-color: #fff;
        padding: 15px;
        opacity: 0.9;
    }
	<section>
            <article>
                <header>
                    <h1>Headline</h1>
                    <h2>Title</h2>
                </header>
                <p>content content content</p>
            </article>
        </section>

【问题讨论】:

  • 您到底想以什么为中心?部分内的article 标签?
  • 是的 - 吉米刚刚帮助了我 - 谢谢大家!
  • 让我们将其标记为正确答案

标签: css html center vertical-alignment


【解决方案1】:

您可以将文章垂直居中,首先将其向下移动 50%,然后将其向上移动 50%,使其居中。

section article {
    position: absolute;
    width: 350px;
    height: auto;
    right: 10%;
    z-index: 2;
    background-color: #fff;
    padding: 15px;
    opacity: 0.9;
    top: 50%; // move down 50% of container
    transform: translateY(-50%); // move up 50% of it's own height  
}

Demo

【讨论】:

  • 非常感谢!我不知道您是否能够使用 css 获得容器的高度。祝你有美好的一天 =)
  • 但是transform缺少浏览器compatibility
  • 我认为现在人们并不关心 IE8。 Support table
猜你喜欢
  • 2013-06-24
  • 2013-10-08
  • 1970-01-01
  • 2013-03-01
  • 2012-06-11
  • 2019-05-29
  • 1970-01-01
  • 1970-01-01
  • 2015-08-05
相关资源
最近更新 更多