有没有办法垂直和水平地居中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*/
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<div class="background">
<div class="content"> some text </div>
</div>
Run Code Online (Sandbox Code Playgroud)
我的问题不是"如何水平和垂直居中一个元素?"的问题.1我之前曾问过我的问题.(只是查看日期).2-我的问题非常清楚,并以黑色为条件:"当窗口小于内容时,内容不会被删除"
Nrc*_*Nrc 143
在尝试了很多东西后,我发现了一种有效的方法.如果它对任何人都有用,我在这里分享.你可以在这里看到它的工作: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;
}
Run Code Online (Sandbox Code Playgroud)
iam*_*sam 135
当你拥有那种奢侈品.还有flexbox,但在撰写本文时并没有广泛支持.
HTML:
<div class="content">This works with any content</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
.content {
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
Run Code Online (Sandbox Code Playgroud)
对于旧的浏览器支持,请查看此线程中的其他位置
Mul*_*gno 47
这是一个演示:http: //www.w3.org/Style/Examples/007/center-example
一个方法(JSFiddle示例)
CSS:
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: table
}
#content {
display: table-cell;
text-align: center;
vertical-align: middle;
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<div id="content">
Content goes here
</div>
Run Code Online (Sandbox Code Playgroud)
另一种方法 (JSFiddle示例)
CSS
body, html, #wrapper {
width: 100%;
height: 100%
}
#wrapper {
display: table
}
#main {
display: table-cell;
vertical-align: middle;
text-align:center
}
Run Code Online (Sandbox Code Playgroud)
HTML
<div id="wrapper">
<div id="main">
Content goes here
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
无论浏览器大小如何,不论div的大小如何,这样做的合法方法是:
div{
margin:auto;
height: 200px;
width: 200px;
position:fixed;
top:0;
bottom:0;
left:0;
right:0;
background:red;
}
Run Code Online (Sandbox Code Playgroud)