Css中實現一個盒子固定寬度,另一個盒子寬度自適應的方法
網上方法很多,個人認為以下兩種思想是最為常用的。
一種是讓第一個盒子脫離文檔流,第二個盒子離左邊有一定距離。
第二種方法是使用flex布局,不過有一些兼容性問題。
直接上代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style type="text/css">
.div1{background: red;}
.div2{background: yellow;}
.way1>.div1{float:left;width: 200px;height:100px;}
.way1>.div2{margin-left: 200px;height: 100px;}
.way2{display: flex;}
.way2>.div1{width: 200px;height: 100px;}
.way2>.div2{flex: 1;height: 100px;}
.way3{position: relative;}
.way3>.div1{width: 200px;height:100px;display: inline-block;}
.way3>.div2{height: 100px;position:absolute;left: 200px;right:0;display: inline-block;}
</style>
<script>
</script>
<body>
<!-- 兩欄式布局,一方固定,一方自適應 -->
<!-- 方法1 浮動布局和margin-left,利用了塊級元素占滿一行的特性-->
<h1>方法2</h1>
<div class="way1">
<div class="div1"></div>
<div class="div2"></div>
</div>
<!-- 方法2 flex布局-->
<h1>方法2</h1>
<div class="way2">
<div class="div1"></div>
<div class="div2"></div>
</div>
<!-- 方法3 display+相對定位絕對定位方法-->
<h1>方法3</h1>
<div class="way3">
<div class="div1"></div>
<div class="div2"></div>
</div>
</body>
</html>