CSS布局(五)
前言
浮动定位CSS表格flex布局(弹性布局、弹性盒子)网格框架如何快速的用html写出一个界面,你可能会觉得很简单,不就是div摆放,表格布局然后调整下样式吗,可真正做的时候有各种居中、浮动等,并且还要考虑到样式兼容、屏幕分辨率等问题。目前CSS布局主要有如下技术:
浮动
所谓浮动就是允许元素浮动到另外一个元素的左侧或者右侧,浮动的框会脱离文档流,也就是他本该占据的位置会空出来。
float 属性有四个可能的值:
1. left — 将元素浮动到左侧。
2. right — 将元素浮动到右侧。
3. none — 默认值, 不浮动。
4. inherit — 继承父元素的浮动属性。
框1右浮动,脱离文档流,直到碰到另一个元素的边缘。
再请看下图,当框 1 向左浮动时,它脱离文档流并且向左移动,直到它的左边缘碰到包含框的左边缘。因为它不再处于文档流中,所以它不占据空间,实际上覆盖住了框 2,使框 2 从视图中消失。
如果把所有三个框都向左移动,那么框 1 向左浮动直到碰到包含框,另外两个框向左浮动直到碰到前一个浮动框。
如下图所示,如果包含框太窄,无法容纳水平排列的三个浮动元素,那么其它浮动块向下移动,直到有足够的空间。如果浮动元素的高度不同,那么当它们向下移动时可能被其它浮动元素“卡住”:
定位
静态定位(Static positioning):是每个元素默认的属性——它表示“将元素放在文档布局流的默认位置——没有什么特殊的地方”。相对定位(Relative positioning):相对于它原始位置进行偏移等操作,没有脱离文档流。绝对定位(Absolute positioning):绝对定位会使元素脱离正常布局流的控制,也就是可以随心所欲的放在哪儿。.固定定位(Fixed positioning):顾名思义就是固定元素在某一个地方(如:网页的置顶按钮)。定位是通过position属性,常用的四种定位类型有:
eg:
HTML代码
<h1>Basic document flow</h1><p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p><p class="positioned">By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height.</p><p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p><p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements will <span>wrap onto a new line if possible (like this one containing text)</span>, or just go on to a new line if not, much like this image will do: <img src="/files/13360/long.jpg"></p>
CSS代码
body {width: 500px;margin: 0 auto;}p {background: aqua;border: 3px solid blue;padding: 10px;margin: 10px;}span {background: red;border: 1px solid black;}
正常布局流效果
相对定位
1、新增CSS代码
.positioned{position: relative;top: 30px;left: 30px; }
2、效果
可以看到黄色部分设置相对定位后,在它正常的布局流中往上和往左偏移了30px。
CSS表格(不怎么用)
不要误以为表格布局不是利用table标签的tr或者td进行布局,而是display属性设置为table、table-row……等属性。
flex布局
非常灵活,可参考超级详细的一篇文章flex布局
网格布局(TODO)
框架
利用框架的话就是bootstrap框架了,主要是它的栅格系统。