html - 在页面上垂直和水平居中 <div> 的最佳方法?

标签 html css alignment vertical-alignment centering

居中的最佳方法 <div>页面上的元素垂直和水平?

我知道 margin-left: auto; margin-right: auto;将以水平居中,但垂直居中的最佳方式是什么?

最佳答案

最好最灵活的方式

这个演示的主要技巧是在元素的正常流动中从上到下,所以 margin-top: auto 设置为零。但是,绝对定位的元素在分配可用空间时的作用相同,并且类似地可以在指定的 topbottom 垂直居中(在 IE7 中不起作用)。

##这个技巧适用于任何大小的div

div {
    width: 100px;
    height: 100px;
    background-color: red;
    
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    
    margin: auto;
}
<div></div>

关于html - 在页面上垂直和水平居中 <div> 的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/356809/

相关文章:

jquery - 添加选项卡时,如何防止 Bootstrap UI 选项卡组件垂直堆叠,以致它们溢出容器的宽度?

html - 如何使用 CSS 在图像上滑动 div?

html - CSS居中容器div

javascript - 在 Javascript 字符串中使用 Bootstrap 的 popover 插件

HTML5 视频在 chrome 中播放但在 IE9 中不播放

html - 如何使用 CSS 在 3d 中旋转两个图像?

html - 如何将 html 中的表单居中并保持问题对齐?

javascript - 在动态元素上使用 on() 处理程序不起作用

css - 调整窗口大小时如何将导航菜单恢复为无序 ListView ?

c - GCC 下与 Cortex-M0 的变量对齐