小编典典

将DIV水平和垂直居中

html

有没有办法在 垂直和水平方向上输入一个DIV, 但这很重要, 当窗口小于内容时,内容将不会被剪切
。div必须具有背景色,宽度和高度。

我总是将div的中心定位为绝对位置和负边距,如提供的示例所示。但是它有一个问题,那就是削减内容的顶部。有没有一种方法可以将div.content居中而不会出现此问题?

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>

我的问题不是重复的“如何在水平和垂直方向上居中放置元素?”1-我的问题曾被问过。(只需检查日期)。2-我的问题非常清楚,以黑色为条件:“当窗口小于内容时,内容将不会被剪切”


阅读 225

收藏
2020-05-10

共1个答案

小编典典

在尝试了很多事情之后,我找到了一种可行的方法。如果对所有人有用,我在这里分享。您可以在这里看到它的运行情况:

.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;
    }
2020-05-10