CSS:带标题的内容之前/之后

Aug*_*ger 15 css title pseudo-element

我可以

div:after {
  content: "hello"
}
Run Code Online (Sandbox Code Playgroud)

但是,我可以hello使用带有标题的文本,以便当我用鼠标悬停它时,会显示标题吗?

谢谢

Pau*_*e_D 17

您不需要伪元素:

JSFiddle演示

p {
    background:lightblue;
    padding:15px;
    margin:15px;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果需要使用伪元素

JSFiddle演示(2)

HTML

<p class="hover-me" title="I Show up on Hover">Some Text</p>
Run Code Online (Sandbox Code Playgroud)

CSS

p {
    background:lightblue;
    padding:15px;
    margin:15px;
    position: relative;
}

p:hover:after {
    position: absolute;
    content:attr(data-title);
    left:0;
    top:0;
    width:200px;
    height:1.25rem;
    background-color: blue;
    color:white;
}
Run Code Online (Sandbox Code Playgroud)

  • 我总体上同意,但这取决于额外的“内容”是什么。 (2认同)
  • 这不是伪元素的内容与标题(工具提示)不同的问题的答案 (2认同)

Amr*_*Amr 6

解决此问题的方法是使用两个伪元素。

例如,::after是主要元素,::before将在悬停时显示并充当标题。

此外,您还可以使用 javascript 或 jQuery 代码来检测伪元素上的鼠标事件。

演示

下面是demo的解释:

$('.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();
    }
});
Run Code Online (Sandbox Code Playgroud)
.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;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="alert">
  <strong>Hover</strong> over X to display the title.
</div>
Run Code Online (Sandbox Code Playgroud)