CSS负边距的几种应用

<style type="text/css">
【1、实现块级元素在块级元素中水平垂直居中】
* ① 设置子容器为定位元素;
* ② left:50%; margin-left:-width/2;
* top:50%; margin-top:-height/2;
*/
.div1{
width: 100px;
height: 100px;
background-color: red;
overflow: hidden;
/*position: relative;*/
}
.div2{
width: 50px;
height: 50px;
background-color: blue;
position: relative;
left: 50%;
margin-left: -25px;

top: 50%;
margin-top: -25px;
}

【2、使用负边距增大元素宽度】
* ① 不指定子容器宽度,指定高度或填充内容;
* ② margin: 0px -50px; 可以是左右两边,均超出父容器50px
*/
.div3{
width: 200px;
height: 50px;
border: 5px dotted #0000FF;
margin: 0 auto;
}
.div4{
background-color: red;
height: 100%;
margin: 0px -50px 0px -50px;
}
/* 第二部分应用,解决div中多个li间距问题
*/
.div5{
width: 170px;
height: 110px;
background-color: #CCCCCC;
}

.div5 ul{
list-style: none;
/*width: 180px;*/
margin-right: -10px;
padding: 0px;
}

.div5 ul li{
width: 50px;
height: 50px;
margin-right: 10px;
margin-bottom: 10px;
background-color: orange;
float: left;
}

【3、负边距实现双飞翼布局】
* ① 由于main部分写在前面,所以可以保证朱布局的优先加载
*/
.main, .sub, .extra {
float: left;
}
.main {
width: 100%;
background-color: #ccc;
}
.sub {
width: 190px;
background-color: #333;
margin-left: -100%;
}
.extra {
width: 230px;
background-color: #000;
margin-left: -230px;
}
.main-wrap {
margin: 0 230px 0 190px;
}


</style>
</head>


<body>
<div class="div1">
<div class="div2">

</div>
</div>

<div class="div3">
<div class="div4">

</div>
</div>

<div class="div5">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>


<div class="container clearfix">
<div class="main">
<div class="main-wrap">
<p>main</p>
</div>
</div>
<div class="sub">
<p>Sub</p>
</div>
<div class="extra">
<p>Extra</p>
</div>
</div>



</body>

posted @ 2017-03-26 21:33  独孤十九剑  阅读(265)  评论(0编辑  收藏  举报