多行文本溢出,三角形图标,鼠标悬浮,水平垂直居中……每天前端开发者们都在和它们打交道,本文收集了一些CSS技巧,希望能够帮助到你们的日常开发。
1. 修改输入框placeholder样式
-webkit-input-placeholder是表单输入框占位符的属性,如何修改此属性样式,如下:
input::-webkit-input-placeholder {
color: #babbc1;
font-size: 12px;
}
2.CSS新增的选择器not、has(此选择器配合一些伪类选择器能够方便我们写好多样式)
div:not(:first-child) {
border-top:1px solid #ccc
background: blue;
}
parent:has(.child) {
background: #fafafa;
color: blue
}
3.控制元素的显示和隐藏,你可以试试content-visibility,可以提高渲染性能
content-visibility: hidden // 元素本身会渲染,但是元素的子元素不渲染
content-visibility: auto // 它可以用来跳过屏幕外的内容渲染,对于这种有大量离屏内容的长列表,可以大大减少页面渲染时间。
4.使用css实现三角形
.triangle {
display: inline-block;
margin-right: 10px; /* 基础样式 */
border: solid 10px transparent;
}
/* 向下三角形 */
.triangle.bottom {
border-top-color: ref;
}
/* 向上三角形 */
.triangle.top {
border-bottom-color: blue;
}
/* 向左三角形 */
.triangle.left {
border-right-color: yellow;
}
/* 向右三角形 */
.triangle.right {
border-left-color: pink;
}
5.css居中方式
- 使用line-height
div{
height: 50px; // line-height一定要和height设置为一样才可以
line-height:50px;
text-align: center
}
- 使用flex布局
// flex-direction: row 的时候
div{
display: flex;
align-items: center; // 垂直居中
justify-content: center; // 水平居中
}
// flex-direction: column 的时候
div{
display: flex;
align-items: center; // 水平居中
justify-content: center; // 垂直居中
}
- 使用grid布局
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
</div>
.container {
display: grid;
/* grid-template-columns属性定义每一列的列宽,grid-template-rows属性定义每一行的行高。 */
grid-template-columns: repeat(4, 60px);
grid-template-rows: repeat(2, 60px);
/* grid-gap属性是grid-column-gap和grid-row-gap的合并简写形式,
grid-row-gap属性设置行与行的间隔(行间距),grid-column-gap属性设置列与列的间隔(列间距)
行与行之间 列与列之间 都是10*/
grid-gap: 10px;
/* item在这个单元格中的位置justify-items属性设置单元格内容的水平位置(左中右),align-items属性设置单元格内容的垂直位置(上中下) */
align-items: center;
justify-items: center;
/* justify-content属性是整个内容区域在容器里面的水平位置(左中右),align-content属性是整个内容区域的垂直位置(上中下)。 */
justify-content: center;
align-content: center;
width: 100%;
height: 500px;
background: #f3f3f3;
}
.item {
width: 30px;
height: 30px;
display: grid;
border: 1px solid red;
justify-content: center;
align-content: center;
}
- 使用决对定位
<div class="container">
<div class="item">我是子元素</div>
</div>
.container{
width: 300px;
height:300px;
border: 1px solid #ccc;
position: relative; // 重要
}
// 知道元素的宽高,可是使用下面方式
.item{
width: 100px;
height: 100px;
border: 1px solid #ddd;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
// 元素的宽高位置,可是使用下面方式
.item{
border: 1px solid #ddd;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
}
今天就先写这么多,如果能够帮助到大家一点点,那我也超级开心😄