CSS: before / after content with title

后端 未结 3 1554
面向向阳花
面向向阳花 2020-12-18 18:49

I can do

div:after {
  content: \"hello\"
}

But can I have the hello text with a title so that when I hover it with the mouse

3条回答
  •  抹茶落季
    2020-12-18 19:25

    A workaround for this, is to have two pseudo elements.

    For example the ::after is the main element and the ::before will be shown on hover and acts like a title.

    Also, you can use javascript or jQuery code to detect mouse events over the pseudo element.

    Demo

    Bellow is the demo explanation:

    $('.alert').on('mousemove', function(e) {
        if (e.offsetX > (this.offsetWidth - 42)) { //42 is the ::after element outerWidth
            $(this).addClass('hover');
        } else {
            $(this).removeClass('hover');
        }
    }).on('mouseleave', function(e) {
        $(this).removeClass('hover');
    }).on('click', function(e) {
        if (e.offsetX > (this.offsetWidth - 42)) { //42 is the ::after element outerWidth
            $(this).remove();
        }
    });
    .alert {
        padding: 15px;
        margin: 50px 0 20px;
        border: 1px solid transparent;
        border-radius: 4px;
        position: relative;
        color: #a94442;
        background-color: #f2dede;
        border-color: #ebccd1;
        font-size: 0.85em;
        transition: all 1s;
    }
    .alert::after, .alert::before {
        content: 'X';
        position: absolute;
        right: 0;
        top: 0;
        width: 40px;
        height: 100%;
        font-size: 0.85em;
        padding: 0;
        line-height: 40px;
        text-align: center;
        font-weight: 900;
        font-family: cursive;
        cursor: pointer;
    }
    .alert::before {
        display: none;
        content: 'This is a Title';
        top: -105%;
        width: auto;
        border: inherit;
        border-radius: inherit;
        padding: 0 0.4em;
        background: rgba(0, 0, 0, 0.48);
        color: white;
    }
    .alert.hover::after {
        color: white;
        filter: sepia(10%);
        transform: scale(1.1);
        border-radius: inherit;
        border: inherit;
        background: inherit;
    }
    .alert.hover::before {
        display: inline-block;
    }
    
    
    
    Hover over X to display the title.

提交回复
热议问题