html+css佈局技巧
阿新 • • 發佈:2018-12-13
(一)、父元素的寬高的變化子元始終素鋪滿父元素
<body> <div class="parent"> <div class="child"></div> </div> </body> <style type="text/css"> .parent{ position: relative; background: blue; width: 800px; height: 800px; margin: 0 auto; } .child{ position: absolute; background: red; top: 0; left: 0; right: 0; bottom: 0; } </style>
(二)、子元素位於父元素正中心
<div class="parent"> <div class="child"></div> </div> <style type="text/css"> .parent{ position: relative; background: blue; width: 50%; height: 500px; margin: 0 auto; } .child{ position: absolute; background: red; width: 100px; height: 100px; top: 0; left: 0; right: 0; bottom: 0; margin: auto; } </style>
(三)、子元素垂直居中
<div class="parent"> <div class="child"></div> </div> <style type="text/css"> .parent{ position: relative; background: blue; width: 50%; height: 500px; margin: 0 auto; } .child{ position: absolute; background: red; width: 100px; height: 100px; top: 0; bottom: 0; margin: auto; } </style>
(四)子元素水平居中
<div class="parent">
<div class="child"></div>
</div>
<style type="text/css">
.parent{
position: relative;
background: blue;
width: 50%;
height: 500px;
margin: 0 auto;
}
.child{
position: absolute;
background: red;
width: 100px;
height: 100px;
left: 0;
right: 0;
margin: auto;
}
</style>
(五)固定寬高比盒子,padding-bottom的取值是參照width,如果width的值是百分比,那麼參照就是父元素的width值
<div class="parent">
<div class="child">
<div class="grandson"></div>
</div>
</div>
<style type="text/css">
body{
height: 900px;
}
.parent{
background: blue;
overflow: hidden;
width: 100%;
height: 0;
padding-bottom: 50%;
margin: 0 auto;
}
.child{
background: red;
overflow: hidden;
width: 50%;
height: 0;
padding-bottom: 50%;
margin: auto;
}
.grandson{
background: yellow;
overflow: hidden;
width: 50%;
height: 0;
padding-bottom: 50%;
margin: auto;
}
</style>