如何将div水平和垂直居中并调整高度以适应内容?
这是我的HTML代码:
<div class="sprite">
</div>
<div class="content">
<span>close</span>
<div class="centered">
lorem lipsum.....
</div>
</div>
和css:
.sprite{
position: fixed;
left: 0px;
top: 0px;
z-index: 20;
width: 100%;
height: 100%;
background-color: gray;
opacity: 0.6;
}
.content{
border:1px solid red;
z-index:21;
position: absolute;
margin:auto;
padding:10px;
left: 0px;
top: 0px;
bottom:0px;
right:0px;
height:30%;
width:30%;
text-align:center;
}
.content span{
position:absolute;
top:0px;
right:0px;}
.centered{
height:100%;
/* Internet Explorer 10 */
display:-ms-flexbox;
-ms-flex-pack:center;
-ms-flex-align:center;
/* Firefox */
display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center;
/* Safari, Opera, and Chrome */
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
/* W3C */
display:box;
box-pack:center;
box-align:center;
}
这就是我想要的:
答案 0 :(得分:10)
编辑.content类以拥有以下css并删除绝对位置
height:auto;
overflow:visible;
答案 1 :(得分:1)
在.content
课程中,删除
position: absolute;
和添加
margin-top:24%;
在取内容高度时将其对齐在垂直中间。
absolute
定位属于相当困难的风格!
小提琴:http://jsfiddle.net/logintomyk/Xxfhn/
编辑
在这里你去交配
CSS修改:
.sprite{
position: fixed;
left: 0px;
top: 0px;
z-index: 20;
width: 100%;
/* height: 100%; */
background-color: gray;
opacity: 0.6;
border:1px solid #FFF;
text-align:center;
}
.content{
border:1px solid red;
position:relative;
z-index: 21; /* change this to less than 20 to overlay under sprite on scroll*/
margin:auto;
padding:10px;
width:30%;
margin-top:24%;
text-align:center;
}
.content span{position:absolute;right:0;top:0;text-align:right; border:1px solid #F00000}
小提琴:http://jsfiddle.net/logintomyk/Xxfhn/2/
诀窍是在absolute
<span>
类中对齐relative
content
....
答案 2 :(得分:0)
用我的css
替换......
.sprite{
position: fixed;
left: 0px;
top: 0px;
z-index: 20;
width: 100%;
height: 100%;
background-color: gray;
opacity: 0.6;
}
.content{
border:1px solid red;
z-index:21;
position: absolute;
margin:auto;
padding:10px;
left: 0px;
top: 0px;
bottom:0px;
right:0px;
width:30%;
text-align:center;
}
.content span{position:absolute; top:0px; right:0px;}
.centered{
/* Internet Explorer 10 */
display:-ms-flexbox;
-ms-flex-pack:center;
-ms-flex-align:center;
/* Firefox */
display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center;
/* Safari, Opera, and Chrome */
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
/* W3C */
display:box;
box-pack:center;
box-align:center;
}
答案 3 :(得分:0)
.content{
border:1px solid red;
position:relative;
margin:auto;
padding:10px;
width:30%;
margin-top:4%;
text-align:center;
}
.content span{position:absolute;right:0;top:0;text-align:right;}
.sprite{
position: fixed;
left: 0px;
top: 0px;
width: 100%;
background-color: gray;
opacity: 0.6;
border:1px solid #FFF;
text-align:center;
}
帮助
答案 4 :(得分:0)
你正在努力做到这一点,只需在班级内容中将职位改为亲戚,见下文;
.content{
border:1px solid red;
z-index:21;
position: absolute;
margin:auto;
padding:10px;
left: 0px;
top: 0px;
bottom:0px;
right:0px;
height:30%;
width:30%;
text-align:center;
}