水平和垂直居中DIV [英] Center a DIV horizontally and vertically

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

问题描述

是否有垂直和水平中心A DIV的方法,但重要的是,当窗口小于内容时内容不会被剪切 div必须有背景颜色和宽度和高度。

Is there a way to CENTER A DIV vertically and horizontally but, and that is important, that the content will not be cut when the window is smaller than the content The div must have a background color and a width and hight.

我一直用div的绝对定位和负边距示例提供。但它的问题是它削减了顶部的内容。有没有一个方法来定位div .content没有这个问题?

I have always centered divs with the absolute positioning and negative margins like in the example provided. But it has the problem that it cuts the content on top. Is there a method to center the div .content without this problem?

我有这里的例子: http://jsbin.com/iquviq/1/edit

CSS:

body { margin: 0px; }

.background {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    background-color: yellow;
}

/* 
is there a better way than the absolute positioning and negative margin to center the div .content: div with background color a width and a hight?: 
*/ 


.content {
    width: 200px;
    height: 600px;
    background-color: blue;

    position:absolute;
    top:50%;
    left:50%;
    margin-left:-100px;/* half width*/
    margin-top:-300px;/* half height*/
}

HTML:

<div class="background">
    <div class="content"> some text </div>
</div>

我的问题不是如何水平和垂直地居中元素之前问。 (只是检查日期)。 2-我的问题很清楚,黑色作为条件:当窗口小于内容时,内容不会被剪切

My question is not duplicate of "How to center an element horizontally and vertically? " 1- My question was asked before. (just check dates). 2- My question ask very clearly and in black as condition: "the content will not be cut when the window is smaller than the content"

推荐答案

在尝试了很多事情后,我发现一种方式工作。我在这里分享它,如果它对任何人有用。您可以在此处看到它: http://jsbin.com/iquviq/30/edit

After trying a lot of things I find a way that works. I share it here if it is useful to anyone. You can see it here working: http://jsbin.com/iquviq/30/edit

.content {
        width: 200px;
        height: 600px;
        background-color: blue;

        position:absolute; /*it can be fixed too*/
        left:0; right:0;
        top:0; bottom:0;
        margin:auto;

        /*this to solve "the content will not be cut when the window is smaller than the content": */
        max-width:100%;
        max-height:100%;
        overflow:auto;
    }

这篇关于水平和垂直居中DIV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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