前端開發CSS使用技巧總結

隱藏盒子的幾種方式

  • overflow:hidden; //隱藏盒子超出的部分
  • display: none; 隱藏盒子,而且不佔位置(用的最多)
  • visibility: hidden; //隱藏盒子,佔位置。
  • pacity: 0; //設置盒子的透明度(不建議,因爲內容也會半透明),佔位置

將盒子移出視窗:

margin-left: -1000px;
left: -999px //把盒子移得遠遠的,佔位置。

  • css畫三角形
/*上三角*/
.triangle{
	width: 0;
	height: 0;
	border-left: 50px solid transparent;
	border-right: 50px solid transparent;
	border-bottom: 50px solid red;
	border-top: 50px solid transparent;
}
  • 設置盒子的半透明
    方式一: pacity: 0.4 。優點是方便。缺點是:裏面的內容也會半透明
    方式二:css3的技術來解決半透明。如下:
background: rgba(0,0,0,0.3);
background: rgba(0,0,0,.3);
備註: a 指的是alpha透明度。
  • 背景圖不能撐開盒子
    使用背景圖的時候要提前定義盒子寬高。

  • 盒子居中
    1、display: block;
    2、必須定寬
    3、左右margin 取值爲auto;

BFC

  • 概念:
    BFC(Block Formatting Context)塊級格式上下文
  • 特性:
  1. 同一個BFC中,垂直方向的margin 會摺疊,不是同一個BFC,不會摺疊
  2. BFC區域不會與float box重疊(可用於排版)
  3. 計算BFC的高度時,浮動元素也參與計算(不會浮動坍塌)
  4. 使用BFC來防止文字環繞
    每個元素的margin box的左邊, 與包含塊border box的左邊相接觸(對於從左往右的格式化,否則相反)。即使存在浮動也是如此。
    BFC是一個隔離的獨立容器,容器裏面的子元素不會影響到外面的元素。反之也如此
  • 如何形成一個BFC?
    1、根元素
    2、float屬性不爲none
    3、position爲absolute或fixed
    4、display爲inline-block, flex, inline-flex,table,table-cell,table-caption
    5、overflow不爲visible, 推薦hidden

margin摺疊問題

  • 概念:在普通文檔流中,兩個相鄰的元素在垂直方向上外邊距會發生摺疊。
  • 當出現margin摺疊時如何計算margin值:
  1. 同是正值,取最大值:30px , 20px ===> 30px
  2. 一正值一負值,取兩者的和:-30px , 20px ===> 10px
  3. 同是負值,取兩者的絕對值的最大值:-30px , -20px ===> -30px
  • 元素水平垂直居中
.parent{
	position: relative;
	width: 300px;
	height: 300px;
	border: 1px solid red;
}
.children{
	width: 100px;
	height: 100px;
	background: pink;
}
<div class="parent c3">
	<div class="children"></div>
</div>
  • margin + transform
.c3{
	margin: 0 auto;
	margin-top: 50%;
	transform: translateY(-50%);
}.c3{
	margin-left: 50%;
	margin-top: 50%;
	transform: translate(-50%, -50%);
}
  • position + transform
.c3{
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
}
  • position + margin
.c3{
	position: absolute;
	left: 50%;
	top: 50%;
	margin-left: -50px;
	margin-top: -50px;
}

.c3{
	position: absolute;
	left: 0;
	top: 0;
	bottom: 0;
	right: 0;
	margin: auto;
}
  • flex
.c3{
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}
精靈圖
  • 精靈圖技術的本質:所謂精靈圖就是把很多的小圖片合併到一張較大的圖片裏,所以在首次加載頁面時候,就不用加載過多的小圖片,只需要加載出來將小圖片合併起來的那一張大圖片也就是精靈圖即可,這樣在一定程度上減少了頁面的加載速度,也一定程度上緩解了服務器的壓力。
  • 使用background-position屬性顯示指定的小圖片。

文本溢出處理

  • 單行文本溢出
/*單行文本溢出處理:*/
.text{
	width: 100px;
	text-overflow: ellipsis;
	overflow: hidden;
	white-space: nowrap;
}
  • 多行文本溢出處理:
.text{
	width: 100px;
	height: 100px;
​    display: -webkit-box;-webkit-box-orient: vertical; // 垂直-webkit-line-clamp: n;   // n表示行數
​    overflow: hidden;
}.text{
	height: 200px;
	width: 300px;
	border: 1px solid red;
	vertical-align: middle;
	display: table-cell;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章