代码:
1 2 3 4 |
<div id="parent">
<div id="floater"></div>
<div id="child">Content here</div>
</div>
|
css
1 2 3 4 5 6 7 8 9 10 11 |
#parent {height: 250px;}
#floater {
float: left;
height: 50%;
width: 100%;
margin-bottom: -50px;
}
#child {
clear: both;
height: 100px;
}
|
这种方法并不喜欢,所以常用的就是这个方法
HTML:
<div id="parent">
<div id="child">我是子元素</div>
</div>
CSS:
#parent {position: relative;}
#child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 50%;
height: 30%;
margin: auto;
}
或者:
#parent {position: relative;}
#child {
position: absolute;
top: 50%;
left: 50%;
height: 30%;
width: 50%;
margin: -15% 0 0 -25%;
}
第三种方法:
#box {
300px;
height: 300px;
background: #ddd;
position: relative;
}
#child {
150px;
height: 100px;
background: orange;
position: absolute;
top: 50%;
margin: -50px 0 0 0;
line-height: 100px;
}
第四种方法:
使用绝对定位和transform:
HTML:<div id="child">
我是一串很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长的文本 </div>
CSS:
#box {
300px;
height: 300px;
background: #ddd;
position: relative;
}
#child {
background: #93BC49;
position: absolute;
top: 50%;
transform: translate(0, -50%);
}