将< div>在页面上垂直和水平? [英] Best way to center a <div> on a page vertically and horizontally?

查看:106
本文介绍了将< div>在页面上垂直和水平?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在页面上垂直和水平放置< 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?

推荐答案

最好最灵活的方式



我的 demo on dabblet.com

The best and most flexible way

My demo on dabblet.com

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

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></div>



CSS:



CSS:

div {
    width: 100px;
    height: 100px;
    background-color: red;

    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;

    margin: auto;
}

这篇关于将&lt; div&gt;在页面上垂直和水平?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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