css中两栏布局左边固定右边自动方案

文章类型:CSS

发布者:hp

发布时间:2023-05-20

在开发管理系统中,经常会使用左边固定,右边自动,比如左边菜单,右边内容,今天,整理一下方案

一:float + margin

.box {
	   height: 200px;
	  }

	  .box > div {
		height: 100%;
	  }

	  .box-left {
		width: 200px;
		float: left;
		background-color: blue;
	  }

	  .box-right {
		margin-left: 200px;
		background-color: red;
	  }

二:利用calc计算宽度

.box {
	   height: 200px;
	  }

	  .box > div {
		height: 100%;
	  }

	  .box-left {
		width: 200px;
		float: left;
		background-color: blue;
	  }

	  .box-right {
		width: calc(100% - 200px);
		float: right;
		background-color: red;
	  }

三:float + overflow实现

.box {
	   height: 200px;
	  }

	  .box > div {
		height: 100%;
	  }

	  .box-left {
		width: 200px;
		float: left;
		background-color: blue;
	  }

	  .box-right {
		overflow: hidden;
		background-color: red;
	  }

四:flex

.box {
		height: 200px;
		display: flex;
	  }

	  .box > div {
		height: 100%;
	  }

	  .box-left {
		width: 200px;
		background-color: blue;
	  }

	  .box-right {
		flex: 1; // 设置flex-grow属性为1,默认为0
		overflow: hidden;
		background-color: red;
	  }

五:Grid布局

.container {
  display: grid;
  grid-template-columns: 200px 1fr; /* 左边固定宽度,右边自动占据剩余空间 */
}

.left-column {
  /* 不需要特别的样式,会自动占据左侧固定宽度 */
}

.right-column {
  /* 不需要特别的样式,会自动占据剩余空间 */
}

六:绝对定位

.container {
  position: relative;
  min-height: 100vh; /* 可根据实际情况调整容器高度 */
}

.left-column {
  position: fixed;
  width: 200px; /* 左边固定宽度 */
  top: 0;
  bottom: 0;
  background-color: #f1f1f1; /* 左边固定内容背景颜色 */
}

.right-column {
  margin-left: 200px; /* 右边内容的左边距等于左边固定内容的宽度 */
  padding: 20px; /* 可根据实际情况调整右边内容的内边距 */
  background-color: #ffffff; /* 右边自动内容背景颜色 */
}

七:flex+absolute

.container {
  display: flex;
  position: relative;
}

.left-column {
  width: 200px; /* 左边固定宽度 */
}

.right-column {
  flex: 1; /* 右边自动占据剩余空间 */
  margin-left: 20px; /* 可根据实际情况调整右边内容的左外边距 */
  position: relative;
}

.right-column::before {
  content: "";
  position: absolute;
  top: 0;
  left: -20px; /* 左边固定内容的宽度加上右边内容的左外边距 */
  width: 20px; /* 右边内容的左外边距 */
  height: 100%;
  background-color: #f1f1f1; /* 左边固定内容的背景颜色 */
}


评论
0条评论遵守法律,文明用语,共同建设文明评论区

暂无评论,快来发表第一条评论吧~