首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使DIV水平和垂直居中

使DIV水平和垂直居中
EN

Stack Overflow用户
提问于 2013-01-02 22:43:40
回答 6查看 403.8K关注 0票数 152

有没有办法在垂直和水平方向上剪切DIV,但是,很重要的一点是,当窗口比小时,内容不会被剪切。 div必须有背景色和宽度和高度。

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

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

CSS:

代码语言:javascript
复制
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:

代码语言:javascript
复制
<div class="background">
    <div class="content"> some text </div>
</div>

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

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2013-02-12 00:50:00

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

代码语言:javascript
复制
.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;
}
票数 175
EN

Stack Overflow用户

发布于 2014-05-17 04:00:31

适用于现代浏览器

当你有这种奢侈的时候。也有flexbox,但在撰写本文时还没有得到广泛的支持。

HTML:

代码语言:javascript
复制
<div class="content">This works with any content</div>

CSS:

代码语言:javascript
复制
.content {
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

CodepenJSBin上进一步修改它

对于较旧的浏览器支持,请在此线程中的其他地方查找。

票数 205
EN

Stack Overflow用户

发布于 2013-01-02 22:53:40

这是一个演示:http://www.w3.org/Style/Examples/007/center-example

A method (JSFiddle example)

CSS:

代码语言:javascript
复制
html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    display: table
}
#content {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}

HTML:

代码语言:javascript
复制
<div id="content">
    Content goes here
</div>

Another method (JSFiddle example)

CSS

代码语言:javascript
复制
body, html, #wrapper {
    width: 100%;
    height: 100%
}
#wrapper {
    display: table
}
#main {
    display: table-cell;
    vertical-align: middle;
    text-align:center
}

HTML

代码语言:javascript
复制
<div id="wrapper">
<div id="main">
    Content goes here
</div>
</div>
票数 54
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14123999

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档