左右布局
假如有以下的情況(示例),可以使用浮動來達成左右布局的目的。
HTML如下:
<body>
<div class="father clearfix">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
CSS可以這么寫:
<style type="text/css">
.clearfix:after{
visibility: hidden;
display: block;
font-size: 0;
content: "";
clear: both;
height: 0;
}
.father{
width: 600px;
height: 600px;
color: black;
}
.left{
width: 200px;
height: 200px;
color: yellow;
float: left;
}
.right{
width: 200px;
height: 200px;
color: red;
float: left;
margin-left: 100px;
}
</style>
清除浮動可以使用clearfix類。
左中右布局
和左右布局類似,左中右布局也可以通過浮動以及微調幾個塊之間的間距來實現。
HTML如下:
<body>
<div class="father clearfix">
<div class="left"></div>
<div class="middle"></div>
<div class="right"></div>
</div>
</body>
CSS如下:
<style type="text/css">
.clearfix:after{
visibility: hidden;
display: block;
font-size: 0;
content: "";
clear: both;
height: 0;
}
.father{
width: 600px;
height: 600px;
color: black;
}
.left{
width: 150px;
height: 200px;
color: yellow;
float: left;
}
.middle{
width: 150px;
height: 200px;
color: red;
float: left;
margin-left: 50px;
}
.right{
width: 150px;
height: 200px;
color: red;
float: left;
margin-left: 50px;
}
</style>
水平居中
水平居中有很多種方法,下面可以列舉其中幾種。
通過margin: 0 auto; text-align: center實現CSS水平居中。
下為例子:
<body>
<div class="out">
<div class="inner"></div>
</div>
</body>
注意:這種方法父元素必須指定高度和寬度!
<style>
.out{
height: 200px;
width: 200px;
color: black;
}
.inner{
height: 200px;
width: 200px;
color: black;
margin: 0 auto;
text-align: center;
}
</style>
通過display:inline-block和text-align:center實現CSS水平居中。
<body>
<div class="out">
<div class="inner"></div>
</div>
</body>
<style>
.out{
height: 200px;
width: 200px;
color: black;
display: inline-block;
}
.inner{
height: 200px;
width: 200px;
color: black;
margin: 0 auto;
text-align: center;
}
</style>
通過display:flex實現CSS水平居中。
父元素加上display:flex;flex-direction:column
而子元素align-self:center;
<body>
<div class="out">
<div class="inner"></div>
</div>
</body>
<style>
.out{
height: 200px;
width: 200px;
color: black;
display: flex;
flex-direction: column
}
.inner{
height: 200px;
width: 200px;
color: black;
align-self: center;
}
</style>
這些是我所想到的方法。更多的可以參考CSS水平居中的9種方法
垂直居中
可參考一下鏈接CSS垂直居中的8種方法
其他小技巧
1.塊級元素的高度由其內部文檔流元素的高度的總和決定
2.文檔流:文檔內元素的流動方向
a.內聯元素inline:從左往右流動,若遇到阻礙(寬度不夠)則換行繼續從左往右
word-break:break-all/break-world
文字分割,break-all是所有字符可以換行,break-world是每個單詞才能分開
b.塊級元素block:每一個塊都占一行,從上往下流動
display:inline-block將塊級元素變成行內元素
3.內聯元素的高度:
玄學
font-size比line-height小時,字體自動居中;但字體比line-height大時,內聯元素但高度不可預測
xscope
4.position:fixed 固定在屏幕上,跳出流,元素聚攏
5.絕對定位,脫離流
子元素position:abusolute
父元素position:relative
6.display:inline-block的外邊距不合并