星空网 > 软件开发 > 网页设计

CSS常用布局实现方法

CSS 布局对我来说,既熟悉又陌生。我既能实现它,又没有很好的了解它。所以想总结一下,梳理一下 CSS 中常用的一列,两列,三列布局等的实现方法。本文小白,仅供参考。但也要了解下浮动,定位等。

一、一列布局

1.  居中定宽

这算是最简单且最容易实现的布局了吧。列出最核心的 CSS 代码:

body{text-align: center;font-size: 2em;}.head,.main,.footer{width: 960px;margin: 0 auto;}.main{background-color: #666666;height: 600px;}.footer{background-color: #999999;height: 200px;}

其中,最主要的还是 margin 属性,当为元素设置了宽度,margin:0 auto 就能自动让元素居中。

2. 自适应

这个也非常简单,只需要将上述 CSS 代码中元素的 width 属性设置为百分比,这样就能让浏览器自动计算元素的宽度。

二、两列布局

1. 定宽

这个应该也没什么难度,只需设置好相应的宽度就好了。这里贴出代码:

body{text-align: center;font-size: 2em;}.main{width: 960px;height: 900px;margin: 0 auto;}.left{width: 300px;height: 900px;background-color: #eee;float: left}.right{width: 660px;height: 900px;background-color: #999;float: right;}

  这里涉及到了 float 属性,也就是常说的浮动了。一个向左浮动,一个向右浮动,恰好能实现两列布局。‘

2. 自适应

将 width 属性的值替换成百分比,就是这么简单。

body{text-align: center;font-size: 2em;}.main{width: 80%;height: 900px;margin: 0 auto;}.left{width: 30%;height: 900px;background-color: #eee;float: left}.right{width: 70%;height: 900px;background-color: #999;float: right;}

  注意:父元素也要设置成百分比。

三、三列布局

1. 左右定宽

body{text-align: center;font-size: 2em;margin: 0;padding: 0}.main{height: 900px;background-color: #ddd;margin: 0 240px;}.left{width: 240px;height: 900px;background-color: #eee;position: absolute;top: 0;left: 0}.right{width: 240px;height: 900px;background-color: #999;position:absolute;top: 0;right: 0}

  这里最主要的是用到了绝对定位,并且让中间的 margin 左右为两边的宽度。

2. 自适应

body{text-align: center;font-size: 2em;margin: 0;padding: 0}.main{height: 900px;background-color: #ddd;margin: 0 20%;}.left{width: 20%;height: 900px;background-color: #eee;position: absolute;top: 0;left: 0}.right{width: 20%;height: 900px;background-color: #999;position:absolute;top: 0;right: 0}

  同理,其换成百分比的形式。

四、混合布局

最后来个前面的大综合。

<!DOCTYPE html><html><head>	<meta charset="utf-8">	<meta http-equiv="X-UA-Compatible" content="IE=edge">	<title>混合布局自适应</title>	<link rel="stylesheet" href="">	<style type="text/css">		body{text-align: center;font-size: 2em;margin: 0;padding: 0}		.head,.main,.footer{width: 80%; margin:0 auto;}		.head{background-color: #ccc; height: 100px}		.footer{background-color: #9cc; height: 100px}		.main{position: relative;}		.left{width: 20%;height: 900px; background-color: #eee;position: absolute;top: 0;left: 0; overflow: hidden;}		.middle{height: 900px; background-color: #fcc; margin: 0 20%; overflow: hidden;}		.right{width: 20%; height: 900px; background-color: #eee;position: absolute; top: 0; right: 0;overflow: hidden;}	</style></head><body>	<div >head</div>	<div >		<div >left</div>		<div >middle</div>		<div >right</div>	</div>	<div >footer</div></body></html>

  




原标题:CSS常用布局实现方法

关键词:CSS

CSS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流