要实现如图所示的搜索框:我们可以这样写代码:这里关键是用到了子绝父相的定位,与传统的堆砌标签设置左右边距不同,极大地节省了错误的发生率。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
width: 172px;
height: 30px;
border-bottom: 2px solid #e7e7e7;
}
input{
padding-left: 30px;
width: 172px;
/* 由于父元素div标签有2px的下边距,因此这里input框的高度只能为28px */
height: 28px;
position: relative;
}
input::placeholder{
font-size: 14px;
color: #ccc;
}
span{
position: absolute;
width: 18px;
height: 18px;
display: inline-block;
background-image: url(./images/sprites.png);
background-position: -79px -69px;
left: 13px;
top: 14px;
}
</style>
</head>
<body>
<div class="search">
<input type="text" placeholder="搜一搜">
<!-- 该span标签是为了进行子绝父相使用的 -->
<span></span>
</div>
</body>
</html>