在日常开发中进场会遇到需要两栏并列,左侧定宽,右侧自适应的情况
1.使用float
<style>
.parent{
/*清除浮动*/
position: absolute;
background: yellow;
}
.parent .child-left{
float: left;
width: 100px;
height: 300px;
background: red;
}
.parent .child-right{
background: blue;
height: 300px;
/*使用BFC消除文字环绕*/
overflow: hidden;
/*使用margin或padding消除文字环绕*/
/*padding-left: 100px;*/
/*margin-left: 100px;*/
}
</style>
<div class="parent">
<div class="child-left"></div>
<div class="child-right">很多文字。。。。。。。。</div>
</div>
要注意一下几点:
- 父元素要清除浮动,否则父元素会坍塌。清除浮动参考https://blog.csdn.net/weixin_42729843/article/details/105278213
- 左侧定宽,向左浮动,保证两栏并列
- 右侧不需要再浮动,但是要消除文字环绕,可以使用padding或marin为左侧空出一定距离,或者为右侧定义一个BFC,BFC不会与float重叠
- 不好设置垂直居中
2. 使用绝对定位
既然可以使用浮动让左侧元素不占据父元素的流体空间,从而文案通过block自适应,那么也可以让左侧通过绝对定位脱离正常文档流。
.parent{
position: relative;
}
.parent .child-left{
position: absolute;
}
.parent .child-right{
/*让文字给左侧留出空间*/
margin-left: 100px;
/*padding-left: 100px;*/
}
3. 使用flex布局
.parent{
display: flex;
/*非常容易设置垂直居中*/
align-items: center;
}
.parent .child-left{
flex: 0 0 100px;
}
.parent .child-right{
flex: 1;
}
在这个购物车的实现中,使用左侧右侧使用flex布局实现,在左侧中又有两个子元素(购物车和配送¥9)需要并列布局,这时可以使用float实现。在菜鸟文档中给出解释“设为Flex布局以后,子元素的float、clear和vertical-align属性将失效”,但是在实现中发现,在设为flex的直系子元素中float失效,但是在其第二代子元素中float有效。
4. 使用inline-block
注意inline-block之间会有间隙(3px chrom),可以在包含元素中使用font-size:0消除
5. table布局
<style>
.left{
background-color: red;
width: 100px;
}
.right{
background-color: blue;
}
</style>
<table>
<tbody>
<td class="left"></td>
<td class="right">文字。。。。</td>
</tbody>
</table>
两侧内容自动垂直对齐
6.使用CSS进行table布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>左右布局</title>
<style>
.parent{
background: yellow;
display: table;
}
.parent .child-left{
display: table-cell;
}
.parent .child-right{
display: table-cell;
/*垂直居中*/
vertical-align: middle;
}
</style>
<div class="parent">
<div class="child-left"></div>
<div class="child-right">文字。。。。。</div>
</div>