小编典典

水平和垂直居中 DIV

all

有没有办法使 DIV 垂直和水平居中, 但重要的是, 当窗口小于内容时,内容不会被剪切 div 必须具有背景颜色以及宽度和高度。

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

我这里有例子可以玩: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>

我的问题与“如何使元素水平和垂直居中?”
1-我的问题之前被问过。(只需检查日期)。2-我的问题问得很清楚,而且是黑色的:“当窗口小于内容时,内容不会被剪切”


阅读 87

收藏
2022-09-02

共1个答案

小编典典

在尝试了很多事情之后,我找到了一种可行的方法。如果对任何人有用,我在这里分享。你可以在这里看到它的工作:http:
//jsbin.com/iquviq/30/edit

.content {
        width: 200px;
        height: 600px;
        background-color: blue;
        position: absolute; /*Can also be `fixed`*/
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        /*Solves a problem in which the content is being cut when the div is smaller than its' wrapper:*/
        max-width: 100%;
        max-height: 100%;
        overflow: auto;
}
2022-09-02