使用 CSS 在视口中垂直居中 [英] Vertically center in viewport using CSS

查看:66
本文介绍了使用 CSS 在视口中垂直居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在不使用 Javascript(仅限纯 HTML 和 CSS)的情况下将

在视口(浏览器窗口)中垂直居中.我有几个限制:

  • div 必须在视口中垂直居中. 我见过的方法只支持在另一个

    内居中,这是不是我想要的.
  • div 的高度未知.

其他限制:

  • div 必须向右对齐.
  • div 具有恒定的宽度.
  • div 必须支持填充.
  • 其他元素将放置在网页上.div 充当菜单.
  • div 必须支持背景颜色/图像.

这让我接近我想要的,但不完全是:

#nav {位置:固定;右:0;顶部:50%;}

但是,导航的顶部在中间,而不是导航的中间.

有什么技术可以让我用这些约束将 div 居中?

解决方案

您可以将此作为解决方案之一.

 <样式>#容器{高度:100vh;//vh - 视口高度显示:弹性;弹性方向:列;对齐项目:居中;对齐内容:居中;}#内容 {}</风格><div id="容器"><div id="内容">任何文本
任何高度
任何内容,例如从 DB<br> 生成的任何内容.一切都垂直居中

I am looking to vertically center a <div> in the viewport (browser window) without resorting to Javascript (pure HTML and CSS only). I have several constraints:

  • The div must be centered vertically in the viewport. Methods I have seen only support centering inside another <div>, which is not what I want.
  • The height of the div is not known.

Other constraints:

  • The div must be aligned to the right.
  • The div has a constant width.
  • The div must support padding.
  • Other elements will be placed on the web page. The div acts as a menu.
  • The div must support a background colour/image.

This gets me close to what I want, but not exactly:

#nav {
    position: fixed;
    right: 0;
    top: 50%;
}

However, the top of the nav is in the middle, not the middle of the nav.

Is there some technique which allows me to center my div with these constraints?

解决方案

you can use this as one of the solution.

   <style>
   #containter {
     height: 100vh; //vh - viewport height
     display: flex;
     flex-direction: column;
     align-items: center; 
     justify-content: center;
   }
   #content {}
  </style>

 <div id="containter">
  <div id="content">
    any text<br>
    any height<br>
    any content, for example generated from DB<br>
    everything is vertically centered
 </div>
</div>

这篇关于使用 CSS 在视口中垂直居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆