垂直和水平居中div没有定义的高度

我想在页面的中心显示一个div,而不必为元素定义一个设置高度,以便高度动态地适合页面的内容。 这可能吗? 我愿意使用JS / jQuery解决方案,只要它们有优雅的后备,但我更喜欢纯CSS解决方案。

这是我当前的代码,它将以div为中心,但我必须包含一个高度。

HTML

Lorem ipsum dolor sit amet, minim molestie argumentum est at, pri legere torquatos instructior ex. Vis id odio atomorum oportere, quem modo fabellas sit at, dicat semper est ne. Apeirian detraxit pri eu. No solum accusam has. Ius ne harum mundi clita, eu pro tation audiam.

CSS

 .card { background-color: #1d1d1d; /* IE fallback */ background-color: rgba(29, 29, 29, 0.95); color: #fff; display: inline-block; margin: auto; position: absolute; bottom: 0; top: 0; left: 0; right: 0; padding: 30px 35px; outline: 2px solid #3B3A37; outline-offset: -9px; width: 320px; height: 350px; /*margin: 0 auto;*/ } 

小提琴链接

这个问题与以前的主题有所不同,因为它被问到的时间,与之相比的类似问题是从2011年开始的,其中很多已经改变,并且新的function已经添加到CSS3中,可以更好地满足要求。

你可以通过机top:50%;transform: translateY(-50%);.card

JSFiddle – DEMO或全屏视图

CSS:

 html, body { height:100%; margin: 0px; } .card { background-color: #1d1d1d; /* IE fallback */ background-color: rgba(29, 29, 29, 0.95); color: #fff; padding: 30px 35px; outline: 2px solid #3B3A37; outline-offset: -9px; width: 320px; position: relative; margin: 0 auto; top:50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); -moz-transform: translateY(-50%); -o-transform: translateY(-50%); transform: translateY(-50%); } 

欲了解更多信息:

  • W3.ORG – CSS转换模块级别1

  • Mozilla MDN – CSS转换

如果你想要一个没有指定高度的CSS解决方案:

  • 你可以使用css3 flexbox :

     body { display:flex; align-items:center; } 

    更新小提琴

  • 或者您可以使用翻译技术:

     .card { position: absolute; top: 50%; left:50%; transform: translateX(-50%) translateY(-50%); /* other styles */ } 

    更新小提琴

浏览器支持:

  • flexbox @ caniuse
  • 变换@ caniuse

附注:如果要支持旧浏览器,可能需要js后备