使用 CSS 在视口中垂直居中
我希望在视口(浏览器窗口)中垂直居中
,而不求助于 Javascript(仅限纯 HTML 和 CSS)。 我有几个限制:div
必须在视口中垂直居中。我见过的方法仅支持在另一个内居中,这不是我想要的。
div
的高度未知。
其他限制:
div
必须右对齐。div
具有恒定的宽度。div
必须支持填充。- 其他元素将放置在网页上。
div
充当菜单。 - div 必须支持背景颜色/图像。
这让我接近我想要的,但不完全是:
#nav {
position: fixed;
right: 0;
top: 50%;
}
但是,导航的顶部位于中间,而不是导航的中间。
是否有某种技术可以让我将 div
与这些约束居中?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
那是什么? 花费8年才能得到问题的答案是不是太多了?
好吧,迟到总比不到好!
您真的已经接近解决方案了。 我会用
transform:translate()< /code>
:
根据我可以使用吗?,除了IE8-和Opera Mini(说实话,这是一个相当好的支持)。
我建议您稍微过度处理它,只需添加所有供应商前缀(只是为了确保!):
这是一个向您展示实际操作的代码片段:
希望它仍然与您相关! (我在开玩笑吧,已经8年了)
What's that? Taking 8 years to get the answer to a problem is too much?
Well, better late than never!
You got really close to the solution. I'd do it with
transform: translate()
:According to Can I use?, it is supported by everything except for IE8- and Opera Mini (which, to be honest, is a pretty good support).
I'd recommend you overkill it a bit and just add all of the vendor prefixes (just to make sure!):
Here's a snippet to show it to you in action:
Hopefully it's still relevant to you! (who am I kidding, it's been 8 years)
您可以使用它作为解决方案之一。
you can use this as one of the solution.
更多信息位于源。)
示例:
运行代码段,然后调整此页面的大小(或旋转设备)。 该框保持在“片段视口”的中心。
(More info at the source.)
Example:
Run the snippet and then resize this page (or rotate device). The box stays centered in the "snippet viewport".
最简单的方法是不使用
div
- 使用包含一行和一个单元格的table
。 不幸的是,CSS 不支持垂直对齐,你会发现自己需要在墙上和天花板上编码来完成它。我理解反对我刚刚提出的语义论点 - 在大多数情况下我是语义标记的支持者。 不过,我也相信使用正确的工具来完成正确的工作。 我认为在这种情况下最好牺牲一点纯度以获得可行的简单解决方案。
The easiest way is not to use a
div
- use atable
with one row and one cell. Vertical alignment is woefully unsupported in CSS and you will find yourself coding up the wall and across the ceiling to accomplish it.I understand the semantic argument against what I have just proposed - I am a proponent of semantic markup in most cases. However I also believe in using the right tool for the right job. I believe it is best to sacrifice a little purity in this case for a simple solution that will work.