html内容如下
<div class="wrap">
<div class="left">left</div>
<div class="right">right</div>
</div>
方法一:利用float
.left {
float: left;
width: 200px;
background-color: pink;
height: 50px
}
.right {
height: 50px;
margin-left: 200px;
background-color: blue;
}
.left {
float: left;
width: 200px;
background-color: pink;
height: 50px
}
.right {
overflow: hidden;
height: 50px;
background-color: blue;
}
⚠️:当overflow的取值不是默认值的时候,就会创建BFC(块级格式化上下文,让元素成为隔离独立的容器,且容器内的子元素不会影响到外面的布局),从而起到一些独特的作用。以下元素会在其内部创建BFC区域:
- 根元素:body
- 绝对定位:position 为absolute或者fixed
- 浮动:float 除 none 以外的值
- overflow不等于visible的块盒
BFC的作用:
- 消除浮动,自动高度会计算浮动元素。
- 它的边框盒不会与浮动元素重叠。=>上述例子正是说明此作用
- 不会和它的子元素进行外边距合并。
方法二:利用定位 position
.wrap {position: relative;}
.left {
width: 200px;
height: 50px;
background-color: pink;
}
.right {
position: absolute;
top: 0;
left: 200px;
height: 50px;
background-color: blue;
width:100%
}
⚠️:设置了position为absolute和fixed时元素会脱离正常文档流,不在占据空间
方法三:利用定位 flex
.wrap {display: flex;}
.left {
width: 200px;
background-color: pink;
height: 50px;
}
.right {
flex: 1;
background-color: blue;
height: 50px;
}
方法四:利用 margin负值
.wrap {
width: 100%;
padding: 10px
}
.left {
width: 100px;
height: 400px;
background-color: blue;
}
.right {
width: 100%;
height: 400px;
margin: -400px 0 0 100px;
background-color: green;
}
⚠️:当margin设置成负值时出现的情况如下:
- margin-top 元素自身会向上移动,同时会影响下方的元素会向上移动;
- margin-botom 元素自身不会位移,但是会减少自身供css读取的高度,从而影响下方的元素会向上移动。
- margin-left 元素自身会向左移动,同时会影响其它元素;
- margin-right 元素自身不会位移,但是会减少自身供css读取的宽度,从而影响右侧的元素会向左移动;
方法五:利用grid布局
.wrap {
display: grid;
grid-template-columns: 10px auto;
height: 100px;
}
.left {
background-color: #0f0;
}
.right {
background-color: #f00;
}
方法六:利用table布局
.wrap {
width: 100%;
display: table;
}
.left {
background-color: #0f0;
width: 200px;
}
.right {
width: 100%;
display: table-cell;
background-color: #f00;
}