Best way to center a lt;divgt; on a page vertically and horizontally?(将 lt;divgt; 居中的最佳方式在页面上垂直和水平?)
问题描述
在页面上垂直和水平居中 <div>
元素的最佳方式?
Best way to center a <div>
element on a page both vertically and horizontally?
我知道 margin-left: auto;margin-right: auto;
将在水平方向居中,但垂直居中的最佳方式是什么?
I know that margin-left: auto; margin-right: auto;
will center on the horizontal, but what is the best way to do it vertically, too?
推荐答案
最好最灵活的方式
这个演示的主要技巧是在元素的正常流动中从上到下,所以 margin-top: auto
设置为零.但是,绝对定位的元素在分配可用空间时的作用相同,并且类似地可以在指定的 top
和 bottom
垂直居中(在 IE7 中不起作用).
The best and most flexible way
The main trick in this demo is that in the normal flow of elements going from top to bottom, so the margin-top: auto
is set to zero. However, an absolutely positioned element acts the same for distribution of free space, and similarly can be centered vertically at the specified top
and bottom
(does not work in IE7).
##这个技巧适用于任何大小的div
.
##This trick will work with any sizes of div
.
div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
<div></div>
这篇关于将 <div> 居中的最佳方式在页面上垂直和水平?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 <div> 居中的最佳方式在页面上垂直和水平?


基础教程推荐
- 检查 HTML5 拖放文件类型 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01