CSS布局、居中等其他小技巧

222 阅读2分钟

1、左右布局

浮动

在css中,左右布局可用浮动布局,若有以下结构:

<div class="parent">
  <div class="left"></div>
  <div class="right"></div>
</div>  

设置浮动,并在父级元素中添加 clearfix 类,清除浮动:

.clearfix::after{
  content:'';
  display:block;
  clear:both;
}
.left,
.right{
  float:left;
} 
position绝对定位

为父元素设置position:relative; 为子元素设置position:absolute 。示例代码如下:

.parent{
  position:relative;
}
.leftChild{
  position:absolute;
  left:0;
  top:0;
}
.rightChild{
  position:absolute;
  left:200px;
  top:0;
}

2、左中右布局

float+绝对定位

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
    .clearfix::after{
         content:'';
         display:block;
         clear:both;
    }
        #content{
            position: relative;
            width:100%;
            height:300px;
        }
        .left{
            float: left;
            width: 200px;
            height:100%;
            background-color: #00a0dc;
        }
        .middle{
            position: absolute;
            top:0;
            bottom:0;
            left:200px;
            right: 300px;
            background-color: red;
        }
        .right{
            float: right;
            height:100%;
            width: 300px;
            background-color: #00a0dc;
        }
    </style>
</head>
<body>
<div id="content clearfix">
    <div class="left"></div>
    <div class="middle"></div>
    <div class="right"></div>
</div>
</body>
</html> 

3、如何让汉字左右对齐

使用伪元素将其对齐,效果如图所示:

<!DOCTYPE html>
<html lang="zh-hans">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            border: 1px solid red;
            font-size: 20px;
        }

        span {
            border: 1px solid green;
            display: inline-block;
            width: 5em;
            text-align: justify;
            line-height: 20px;
            overflow: hidden;
            height: 20px;
        }

        span::after {
            content: '';
            display: inline-block;
            width: 100%;
            border: 1px solid blue;
        }
    </style>
</head>

<body>
    <div>
        <span>姓名</span>
        <br>
        <span>联系方式</span>
    </div>
</body>

</html>

4、水平居中

使用margin auto 来左右居中

.content{
  max-width:940px;
  margin-right:auto;
  margin-left:anto;
}

其他小技巧

  • 如在css中添加 display:inline-block;,需再加vertical-aligh : top; ,Vertical-Align,你应该知道的一切
  • css避免出错,应该少些高度和宽度,div的高度由文档流决定,所以书写顺序应按照由内而外的顺序。