css 定位、浮动(清除浮动)与弹性盒子

423 阅读3分钟

CSS Position(定位)

- static      静态定位
- relative    相对定位
- absolute    绝对定位
- fixed       固定定位
- sticky      粘性定位

一、static定位

html中的默认定位方式,其位置会遵循文档流顺序(在排版布局过程中,元素会依照从左到右,从上到下的顺序依次排列)当static定位时,top、bottom、left、right将不会起作用。

.static {

    display: inline-block;

    width: 150px;

    height: 150px;

    background-color: pink;

}

static.png

二、relative定位

相对定位的元素相对其正常位置定位(移动相对定位元素,但它原本所占的空间不会改变 相对定位偏移后,原来位置保留,元素本身会脱离文档流浮动)

.relative {

    display: inline-block;

    width: 150px;

    height: 150px;

    background-color: orange;

    position: relative;

    top: 50px;

    left: 50px;

}

relative.png

三、absolute定位

绝对定位的元素相对于已定位的父元素定位,如果没有,则相对元素定位
!!绝对定位脱离文档流,不占据空间,可与其他元素重叠

.absolute {

    display: inline-block;

    width: 150px;

    height: 150px;

    background-color: red;

    position: absolute;

    top: 180px;

    left: 180px;

}

absolute.png

四、fixed定位

固定位置相对于浏览器窗口定位,即使浏览器滚动,其位置依旧不变

fixed1.png

fixed2.png

五、stiky定位

stiky定位结合了relative定位与fixed定位,主要用在对scroll事件的监听上。当元素距离其父元素的距离达到stiky定位要求时,sticky定位相当于fixed定位,固定在某个位置,未达到要求前,相当于relative定位

CSS Float(浮动)

特性:
1.包裹性
2.高度塌陷
3.块状化
4.无任何margin合并

CSS 的 Float(浮动),会使元素向左或向右移动,其周围的元素也会重新排列。

高度塌陷与清除浮动

高度塌陷是指父元素本来应该包括子元素的高度,但是实际上父元素比子元素的高度要小

<div class="container">

        <div class="box1"></div>

        <div class="box2"></div>

    </div>
.container {

    margin-left: 50px;

    background: red;

}

.box1 {

    float: left;

    width: 200px;

    height: 200px;

    background-color: blue;

}

.box2 {

    width: 400px;

    height: 100px;

    background: cyan;
}

gaodu.png box1浮动后,父元素的高度坍塌。
解决办法:
【1】让父元素触发bfc,这样bfc内的元素就无法影响到外面

.container {

    margin-left: 50px;

    background: red;

    overflow: auto;
}

gaodu2.png 【2】通过为container添加 :: after伪元素,清除左右浮动房子坍塌

.container ::after {

    content: "";

    display: block;

    clear: left;
}

【3】为其父元素的最后添加块级元素并清除浮动

<div class="container">

        <div class="box1"></div>

        <div class="box2"></div>

        <div style="clear: both;"></div>

    </div>

图中因为box1浮动,将box2部分遮住。需要清除浮动,使用bfc清除浮动,让浮动盒区域不叠加到bfc上,所以为box2添加overflow: auto;也可以为box2添加clear:both,但这种方法会使元素下移

fudong.png

fudong1.png

弹性盒子

弹性盒子由弹性容器(Flex container)和弹性子元素(Flex item)组成。
弹性容器通过设置 display 属性的值为 flex 或 inline-flex将其定义为弹性容器。
弹性容器内包含了一个或多个弹性子元素。
( 弹性容器外及弹性子元素内是正常渲染的。弹性盒子只定义了弹性子元素如何在弹性容器内布局。弹性子元素通常在弹性盒子内一行显示。默认情况每个容器只有一行。)

定义

display:flex;
display:inline-flex;

justify-content

适用于伸缩容器元素,用来设置伸缩项目沿着主轴线的对齐方式

justify-content:center;//伸缩项目向第一行中间位置对齐
space-between ;//伸缩项目会平均分布在一行中

tan2.jpg tan1.jpg

align-items

适用于伸缩容器元素,用来设置伸缩项目所在行沿着主轴线的对齐方式

align-items:center;//伸缩项目向侧轴的中间位置对齐

tan3.jpg

align-content

适用于伸缩容器元素,用来设置伸缩行的对齐方式

align-content:center;//各行向伸缩容器中间位置对齐

tan4.jpg