真实案列—展示负边距的在CSS布局中的巧妙应用
案列一 :实现子元素水平、垂直方向居中
这是一个老生常谈的问题,想要实现子元素水平垂直居中有很多种方法。这里主要介绍如何利用负边距实现。
- 思路:绝对定位 首先思路仍是绝对定位的思想,只是子元素利用负边距实现居中定位。
- 步骤如下:利用绝对定位将子元素定位到父元素右下角->利用负边距实现子元素居中
- 完整代码如下
//html
<div class="parent">
<div class="child">这个是需要垂直居中展示的元素</div>
</div>
// css
<style>
.parent{
position:relative;
width:500px;
height:400px;
border:dashed 1px orange;
}
.child{
background:lightgreen;
width: 80%;
height:200px;
/* 将子元素定位到左下角 */
position:absolute;
left:20%; //100%(parent-height)-80%(parent-height)
top:200px; //400(parent-height)-200(child-height)
/* 利用负边距实现居中定位 */
margin-left:-10%; //向左移动父子元素宽度差的一半
margin-top:-100px; //向上移动父子高度差的一半
}</style>
从这个案列来看负边距好像没有什么巧妙之处,的确,这里只是为了演示负边距的作用效果:
- margin-left 为负,元素向左移动
- margin-top 为负,元素及其后续元素向上移动
- margin-righjt 为负,元素自身不动,或导致右侧元素左移
- margin-bottom 为负,元素自身不动,底部元素上移
顺便一提: 水平垂直居中的最佳方案是采用Flex布局(前提是浏览器支持)
案列二:多栏布局-等宽间距(space-between效果)
正如标题所说,上图所示布局可以通过flex布局实现,利用负边距又如何实现这种效果呢?
- 主要思路:通过
margin-right:-10px
增加元素的宽度,使之可以完全容纳三个元素(直接增加元素宽度也是可行的)
- 完整代码
// html
<div class="box">
<div class="parent">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
</div>
</div>
//css
<style>
.box{
width:320px;
margin:50px;
overflow:hidden; /*构建BFC,避免高度塌陷*/
border:dashed 1px orange;
}
.parent{
/* 通过负边距使得parent宽度增加10px */
margin-right:-10px;
/* 其实也可直接令parent宽度为320px(box-width)+10px */
/* width:330px; */
}
.child{
float:left;
width:100px;
height:100px;
margin-right:10px;
background:lightgreen;
text-align: center;
font-size:20px;
color:red;
}
</style>
注意:想要通过margin改变元素的宽度,那么元素必须满足能自适应填满父级,那本例来说,不能直接给parent元素设置宽度,必须在外层嵌套box元素,从而保证利用块级元素特性,是parent自适应充满box,这时方可通过
margin-right:-10px
增加parent宽度。
具体细节可查阅张鑫旭《CSS世界》“激进的margin属性”。
案例三:圣杯|双飞翼布局
这两个布局早已司空见惯,这里就不再演示了。挂个链接,有需要的可以去看看。
🚀圣杯|双飞翼布局|
- 圣杯|双飞翼布局思路:
圣杯/双飞翼布局相比其它布局方式,主要解决的一个问题就是让主体区域(中间宽度自适应区域)先于左右固定区域加载。安装正常的布局方式,页面结构通常是左|中|右
或者左|右|中
,而圣杯|双飞翼
布局则是将左右两侧均放置到主体后面,然后left
区域通过设置**margin-left:-100%
**使其上移至主体区域右侧。
案例四:两栏等高布局
- 这个例子直接参考自《CSS世界》这里祭出原文地址🚀Demo
- 代码如下
//html
<div class="wrap">
<div class="left">
<h1>内容1</h1>
<h1>内容1</h1>
<h1>内容1</h1>
<h1>内容1</h1>
</div>
<div class="right">
<h1>内容2</h1>
</div>
</div>
//css
<style>
.wrap{
overflow: hidden;
}
.left,
.right{
width:100px;
float: left;
margin-bottom: -9999px;
padding-bottom: 9999px;
}
.left{
background:lightgreen;
}
.right{
background:orange;
}
</style>
结语
本文主要介绍了负边距在CSS布局中的巧妙使用,对于现代浏览器可能上诉方案以已经不是完美的解决方案,但若需要兼容低版本浏览器,则可以从上诉思路出发,实现版本兼容。
(完)