【前端】使用样式选择器before和after布局,以及简单的表单输入框布局

128 阅读1分钟

我正在参加「掘金·启航计划」

本篇文章来讲解下样式选择器before和after的用法,以及doctype的作用
有时候真的需要温故而知新,用了那么多年的前端,对一些知识点灵活运用加点小技巧也是挺有趣的

【before选择器】

1)本身含义,向选定的元素之前插入内容

div:before{
    content:'hello world!'
}

image.png

2)关键属性content

使用content 属性来指定要插入的内容

3)大部分浏览器都已经支持before选择器,同时需要在html前声明doctype

【after选择器】

1)本身含义,向选定的元素之后插入内容

.div:before{
    content:'hello'
}
.div:after{
    content:'world!'
}
<div class="div">===</div>

image.png

2)关键属性content
使用content 属性来指定要插入的内容
3)大部分浏览器都已经支持after选择器,同时需要在html前声明doctype

【文本框before和after的运用】

1)有上面基础知识点的了解,就可以开始发挥想象了

2)在前端项目开发,表单里用的最多的就是文本框前加星好,标识必填选项

3)设置一个div包含一个input布局

4)在div前插入文本值,在div后面插入星号值

5)文本和星号值以及input都属于行内元素,如果设置input占宽度100%,那么就会出现如下效果,当然这不是我们想要的布局效果

image.png

<style>
    .input-div {
        width: 100%;
        height: 40px;
        line-height: 40px;
        border-bottom: 1px solid #ccc;
    }

        .input-div:before {
            content: '姓名:';
            color: #555;
            font-size: 15px;
        }

        .input-div:after {
            content: '*';
            color: #f00;
            font-size: 15px;
        }
</style>
<div style="width:300px;height:500px;background:#fff;padding:10px;margin:0 auto;margin-top:30px;border-radius:10px;box-shadow:0 0 13px #ccc;">

    <div class="input-div">
        <input />
    </div>

</div>

6)可以使用相父级div定位,将文本和星号分别布局在左右两边,并设置input让出一定左右内编辑,这样也不影响重叠输入值,效果如下

image.png

<style>
    .input-div {
        width: 100%;
        height: 40px;
        line-height: 40px;
        border-bottom: 1px solid #ccc;
        position: relative;
    }

        .input-div:before {
            color: #555;
            font-size: 15px;
            position: absolute;
            top: 2px;
            left: 0px;
            padding-left: 10px;
        }

        .input-div:after {
            content: '*';
            color: #f00;
            font-size: 15px;
            position: absolute;
            top: 4px;
            right: 0px;
        }

    .input {
        width: calc(100% - 120px);
        padding: 0 20px 0 80px;
        border: none;
        background: none;
        outline: none;
    }

    .name:before {
        content: '姓名:';
    }

    .nick:before {
        content: '昵称:';
    }

</style>
<div style="width:300px;height:500px;background:#fff;padding:10px;margin:0 auto;margin-top:30px;border-radius:10px;box-shadow:0 0 13px #ccc;">

    <div class="input-div name">
        <input class="input" placeholder="请输入值姓名" />
    </div>

    <div class="input-div nick">
        <input class="input" placeholder="请输入值昵称" />
    </div>

</div>