伪类和伪元素
- 伪类专门用来表示元素的一种特殊的状态。比如:访问过的链接,普通的链接,获取焦点文本框
- 伪元素表示元素中的一些特殊的位置。比如::before表示元素最前面的部分
- CSS中,::before 创建一个伪元素,其将成为匹配选中的元素的第一个子元素。常通过 content属性来为一个元素添加修饰性的内容。此元素默认为行内元素。
- 在CSS3中,通过::创建伪元素,通过:选中伪类。浏览器也接收将::before写做:before
封装一个有前缀和后缀的input输入框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.my_input {
position: relative;
width: 180px;
}
.my_input_inner {
/* input输入框默认的display就是inline-block */
/* 设置box-sizing */
box-sizing: border-box;
/* 宽度为100% */
width: 100%;
height: 40px;
/* 设置输入框的边框颜色 */
border: 1px solid orange;
/* 设置outline为none,否则在input状态为focus时会有外边框 */
outline: none;
/* 设置输入框的背景颜色 */
background-color: gray;
/* 设置输入框的圆角 */
border-radius: 10px;
/* 设置光标以及文本的颜色 */
color: yellowgreen;
font-size: inherit;
/* 设置左右内边距为30px 用于展示图标 */
padding: 0 30px;
transition: border-color .2s cubic-bezier(.645,.045,.355,1);
}
.my_input_inner:focus {
/* 设置input状态为focus时的边框颜色 */
border: 1px solid red;
}
.my_input_suffix {
/* 开启绝对定位 */
position: absolute;
/* 确定位置 */
right: 5px;
/* 设置高度 */
/*
高度为百分比
当前元素的position为absolute
所以它的包含块是离它最近的position的值不是static的祖先元素的内边距区域
所以百分比是相对于div.my_input的内容区高度而言
*/
height: 100%;
top: 0;
text-align: center;
transition: all .3s;
pointer-events: none;
}
.my_input_suffix_icon {
/* 设置display为inline-block */
display: inline-block;
/* 设置宽度 */
width: 25px;
/* 设置高度 */
/*
高度为百分比
当前元素的position为static
所以它的包含块是离它最近的祖先块元素 也就是span.my_input_suffix
所以百分比是相对于span.my_input_suffix的内容区高度而言
*/
height: 40px;
/* 设置行高和 */
/*
设置line-height为40px
内部元素会在line-height中居中
这样就能呈现视觉上的垂直居中
*/
line-height: 40px;
/* 设置行内的内容水平居中 */
text-align: center;
}
.my_input_suffix_icon:before {
color: pink;
font-style: normal;
content: 'X';
}
.my_input_preffix {
position: absolute;
left: 5px;
height: 100%;
top: 0;
text-align: center;
transition: all .3s;
pointer-events: none;
}
.my_input_preffix_icon {
display: inline-block;
width: 25px;
height: 40px;
/* 这里我们换一种垂直对齐方式 */
/* 这里不设置line-height */
/* line-height: 40px; */
text-align: center;
}
.my_input_preffix_icon:before {
color: pink;
/* 设置高度 */
height: 100%;
/* 通过flex来垂直对齐before中的内容 */
display: flex;
align-items: center;
font-style: normal;
content: 'X';
}
</style>
</head>
<body>
<div class="my_input">
<input type="text" class="my_input_inner">
<span class="my_input_suffix">
<i class="my_input_suffix_icon"></i>
</span>
<span class="my_input_preffix">
<i class="my_input_preffix_icon"></i>
</span>
</div>
</body>
</html>
总结
上面的例子,我们将伪元素垂直居中了,输入框前缀的X采用的是line-height来设置的垂直居中方式。输入框后缀的X采用的是flex来设置的垂直居中方式。
前缀:设置i标签中的伪元素before和input输入框的高度一样高,并且设置伪元素的line-height和input输入框的高度一样高,那么文本就会在before伪元素中垂直居中,也就是在input中垂直居中了。
后缀:设置i标签的display属性为flex,并设置内容垂直居中。那么before伪元素就会在i标签中垂直居中,before伪元素没有设置高度,高度有文本X撑开的。
更多居中方案参考博客:css水平居中方案 垂直居中方案 块级/内联元素居中方案
参考
参考博客:https://www.cnblogs.com/mycoke/p/6056187.html
参考博客:https://www.itranslater.com/qa/details/2582556896884425728