CSS布局

水平居中

1. 行内元素的居中

对父元素设置 text-align:center;

.parent {
  text-align: center;
}
2. 块状元素居中
  • 已定宽块状元素,设置左右 margin值为 auto;
.parent {
  height: 100px;
  width: 400px;
  background: black;
}

.child {
  width: 100px;
  height: 100px;
  background: #4fc08d;
  margin: 0 auto;
}
  • 未定宽块状元素,设置子元素为display:inline,然后在父元素上设置text-align:center;
.parent {
  height: 100px;
  width: 400px;
  background: black;
  text-align: center;
}

.child {
  width: 100px;
  height: 100px;
  background: #4fc08d;
  display: inline-block;
}

垂直居中

1. 内联元素
  • 父元素一定,子元素为单行内联文本:设置父元素的height等于行高line-height;
.parent {
  height: 40px;
  line-height:40px;
}
  • 父元素一定,子元素为多行内联文本:设置父元素的display:table-cell或inline-block,再设置vertical-align:middle;
.parent {
  height: 80px;
  width: 200px;
  display: table-cell;
  vertical-align: middle;
  background-color: red;  
}
2. 块状元素

设置子元素position:fixed(absolute),然后设置margin:auto;

左右布局

1. 左右固定宽度
  • 子元素宽度总和不能大于父元素的宽度。
<body>
  <div>
    <div class="left"></div>
    <div class="right"></div>  
  </div>
</body>
</html>
div {
  width: 600px;
  height: 100%;
  background-color: #efefef;
}
.left {
  background-color: lightblue;
  width: 180px;
  height: 100%;
  float: left;
}
.right {
  background-color: lightgreen;
  width: 400px;
  height: 100%;
  float: left;
  margin-left: 20px;  
  }
2. 左侧固定宽度,右侧自适应
  • 左侧设置固定宽度并设置浮动float:left;
  • 右侧不设置宽度,只间距margin-left(左侧栏宽度+左右栏之间间距)。
<body>
  <div>
    <div class="left"></div>
    <div class="right"></div>  
  </div>
</body>
</html>
div {
  width: 600px;
  height: 100%;
  background-color: #efefef;
}
.left {
  background-color: lightblue;
  width: 180px;
  height: 100%;
  float: left;
}
.right {
  background-color: lightgreen;
  height: 100%;
  margin-left: 190px;  
}
3. 左右自适应
  • 不要使用固定值,用百分比来设置宽度
<body>
  <div>
    <div class="left"></div>
    <div class="right"></div>  
  </div>
</body>
</html>
div {
  width-max: 600px;
  height: 100%;
  background-color: #efefef;
}
.left {
  background-color: lightblue;
  width: 20%;
  height: 100%;
  float: left;
}
.right {
  background-color: lightgreen;
  height: 100%;
  margin-left: 22%;
}

效果截图


左中右布局

1. 左右固定宽度,中间宽度自适应
  • 使用浮动来布局
<body>
  <div>
    <div class="left"></div>
    <div class="right"></div>  
    <div class="middle"></div>
  </div>
</body>
</html>
div {
  width: 600px;
  height: 100%;
  background-color: #efefef;
}
.left {
  background-color: lightblue;
  width: 100px;
  height: 100%;
  float: left;
}
.middle {
  background-color: orange;
  height: 100%;
}
.right {
  background-color: lightgreen;
  width: 100px;
  height: 100%;
  float: right;
}

效果截图


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容