CSS布局技巧(待补充)

1、 两列布局

  • float +clearfix
<div class="content1 clearfix">
    <div class="left1">
        left
    </div>
    <div class="right1">
        right
    </div>
</div>
.left1 {
  float: left;
  background-color: red;
  width: 30%;
}

.right1 {
  float: left;
  background-color: green;
  width: 70%;
}

.clearfix::after {
  content: '';
  display: block;
  clear: both;
}

效果图:
float+clearfix

  • flex布局
<div class="content2">
    <div class="left2">
        left
    </div>
    <div class="right2">
        right
    </div>
</div>
.content2 {
    display: flex;
}

.left2 {
    background-color: red;
    flex-grow: 1;
}

.right2 {
    background-color: green;
    flex-grow: 2;
}

效果图
flex

  • table+table-cell(父元素宽度固定)
<div class="content3">
    <div class="left3">
        left
    </div>
    <div class="right3">
        right
    </div>
</div>
.content3 {
    display: table;
    table-layout:fixed;
    width: 1000px;
}

.left3 {
    display: table-cell;
    background-color: red;
    width: 30%;
}

.right3 {
    display: table-cell;
    background-color: green;
    width: 70%;
}

效果图
table+table-cell

  • position定位(左边一列宽度固定)
<div class="content4">
    <div class="left4">
        left
    </div>
    <div class="right4">
        right
    </div>
</div>
.content4 {
    position: relative;
    height: 21px;
}

.left4 {
    width: 100px;
    position: absolute;
    background-color: red;
    left: 0px;
}

.right4 {
    left: 100px;
    right: 0px;
    position: absolute;
    background-color: green;
}

效果图
position
2、 三列布局可以沿用两列布局的方法
3、 水平居中
- 需要居中inline元素或inlne-block元素

<div class="content1">
    哈哈
</div>
.content1 {
    text-align: center;
}

效果图
text-align

  • 需要居中一个block元素
.content1 {
    background-color: red;
    width: 100px;
    margin: 0 auto;
    text-align: center;
}

margin

  • 需要居中多个block元素
    法一:将元素display: inline-block,再利用上面的text-align:center
    法二:flex布局
<div class="content2">
   <div>哈哈1</div>
   <div>哈哈2</div>
   <div>哈哈3</div>
</div>
.content2 {
    display: flex;
    justify-content: center;
}

效果图
flex
4、 垂直居中
- 需要居中inline元素或inlne-block元素
单行:设置height与line-height相等或设置相同的padding-top和padding-bottom
多行:设置相同的padding-top和padding-bottom
- 需要居中一个block元素
1) 高度已知

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  height: 100px;
  margin-top: -50px; 
  sizing: border-box; 
}

2)高度未知

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
  • 需要居中多个block元素
    flex布局
.parent {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

猜你喜欢

转载自blog.csdn.net/m0_38102188/article/details/80823572