CSS 浮动与定位
# CSS 浮动与定位
## display
- display
- 块 block
- 行内 inline
- 行内块 inline-block
- none
### block
块元素独占一行可以设置宽高
```css
a {
display: block;
width: 200px;
height: 200px;
background-color: red;
}
```

### inline
行内元素并排排列,不可设置宽高(img是特殊的行内元素可以设置)。
```css
<style type="text/css">
div {
display: inline;
background-color: blue;
}
</style>
```

### inline-block
行内块 既能设置宽高 又有行内元素并排排列的特点。
```css
a {
display: inline-block;
background-color: blue;
width: 50px;
height: 50px;
color: #000;
}
```

### none
设置为不显示 可用于隐藏元素
## 浮动
- 浮动 float
- 左浮动 left
- 右浮动 reght
- 两端对齐
- 浮动塌陷
### 浮动样式
左浮动右浮动都是向父元素的最左侧或最右侧浮动,右浮动会改变标签顺序
```css
ul>li {
list-style: none;
float: left;
}
```
```html
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
```

设置为右对齐时

两端对齐样式
```css
div {
width: 100px;
height: 100px;
background-color: red;
}
.right {
float: right;
}
.left {
float: left;
}
```
```html
<div class="right">左</div>
<div class="left">右</div>
```

### 浮动塌陷
在父子元素嵌套时,子元素浮动,父元素需设置高度,在不设置高度的情况下会导致父元素塌陷
```css
.wai {
width: 100%;
border: 1px blue solid;
}
.nei {
float: left;
width: 100px;
height: 100px;
background-color: red;
}
```
```html
<div class="wai">
<div class="nei">子元素</div>
</div>
```

可通过在父元素中添加 overflow: hidden;解决浮动塌陷。
```css
.wai {
width: 100%;
border: 1px blue solid;
overflow: hidden;
}
```

## 定位
- 定位 position
- 相对定位 relative
- 绝对定位 absolute
- 固定定位 fixed
- z-index
HTML里所有元素的position默认都是static,遵从标准文档流,从上至下,方向值、层叠索引值不生效
### 相对定位
定位的元素不会脱离文档流,会相对字节原有位置进行移动,原有位置不会被占用,定位都可设置定位的位置与叠层优先级,设置定位后可设置叠层优先级z-index;默认设置定位后的元素比未设置的优先级高。
可通过设置top,bottom,left,reght调整定位位置。
```css
div {
width: 100px;
height: 100px;
background-color: blue;
border: 1px red solid;
}
.one {
position: relative;
top: 10px;
left: 10px;
}
```
```html
<div class="one">
1
</div>
<div class="two">
2
</div>
<div class="three">
3
</div>
```

### 绝对定位
定位的元素会脱离文档流,原有位置会被其他元素占据,优先级特性与绝对定位相同。
```css
.two {
position: absolute;
top: 30px;
left: 30px;
}
```

可通过设置父相子绝进行水平垂直居中定位
```css
.one {
position:relative;
width: 400px;
height: 400px;
border: 1px red solid;
}
.two {
position: absolute;
width: 50px;
height: 50px;
background-color: blue;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
```
```html
<div class="one">one
<div class="two">two</div>
</div>
```

### 固定定位
定位的元素会固定会到浏览器中固定的位置,不随滚动条拖动改变,参照物是浏览器,即使父元素是relative也无效,优先级特性与绝对定位相同。
```css
.three {
position: fixed;
bottom: 10px;
}
```

### z-index
设置z-index 可设置叠层优先级,优先级越大越靠前。
```css
.one {
position: relative;
top: 10px;
left: 10px;
z-index: 1;
}
```

## 盒子圆角,阴影
### 圆角与阴影
盒子边框圆角通过border-radius进行设置,可设置一个或多个,多个为顺时针设置
设置方形盒子圆角半径和盒子边长一半相同时生成圆形
```css
div {
width: 100px;
height: 100px;
background-color: blue;
border: 1px red solid;
}
.one {
border-radius: 20px;
}
.two {
border-radius: 50px;
}
```
```html
<div class="one"></div>
<div class="two"></div>
```

阴影可通过box-shadow进行设置,可设置阴影的x,y轴位置与晕影大小和颜色
```css
.three {
box-shadow: 5px 10px 5px darkgray;
}
```
```html
<div class="three"></div>
```


浙公网安备 33010602011771号