Pseudo elements and SELECT tag

前端 未结 3 917
臣服心动
臣服心动 2020-12-02 21:56

Does the select tag allows to use the :after selector in order to create a pseudo element after it?

I\'ve tried on Chrome, Safari and Fire

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 22:39

    This is a modern solution I cooked up using font-awesome. I'm not sure how cross-browser friendly it is. Vendor extensions have been omitted for brevity.

    HTML

    SCSS

    fieldset {
        .select-wrapper {
            position: relative;
    
            select {
                appearance: none;
                position: relative;
                z-index: 1;
                background: transparent;
    
                + i {
                    position: absolute;
                    top: 40%;
                    right: 15px;
                }
            }
        }
    

    If your select element has a defined background color, then this won't work as this snippet essentially places the Chevron icon behind the select element (to allow clicking on top of the icon to still initiate the select action).

    However, you can style the select-wrapper to the same size as the select element and style its background to achieve the same effect.

    Check out my CodePen for a working demo that shows this bit of code on both a dark and light themed select box using a regular label and a "placeholder" label and other cleaned up styles such as borders and widths.

提交回复
热议问题