CSS:如何在CSS中正确实现工具提示

时间:2019-01-31 08:55:26

标签: css

下面的代码将鼠标悬停在右侧时,使用css在右侧显示了工具提示

Right Side Tooltip

请将鼠标悬停在名称的顶部上,如何使工具提示出现

<html><head>
</head>
<body>

<div data-tooltip="I am Nancy Moore">
<label>Name</label>
</div>
<style>
div:hover:before {
    content: attr(data-tooltip);
    position: absolute;
    padding: 5px 10px;
    margin: -3px 0 0 50px;
    background: black;
    color: white;
    border-radius: 3px;
}

div:hover:after {
    content: '';
    position: absolute;
    margin: 6px 0 0 3px;
    width: 0;
    height: 0;
    border-top: 5px solid transparent;
    border-right: 10px solid black;
    border-bottom: 5px solid transparent;
}


</style>
</body></html>

3 个答案:

答案 0 :(得分:1)

将边距设置为0并设置z-index:1

margin: -3px 0 0 0;

div:hover:before {
    content: attr(data-tooltip);
    position: absolute;
    padding: 5px 10px;
    margin: -3px 0 0 0;
    background: black;
    color: white;
    border-radius: 3px;
    z-index:1
}

div:hover:after {
    content: '';
    position: absolute;
    margin: 6px 0 0 3px;
    width: 0;
    height: 0;
    border-top: 5px solid transparent;
    border-right: 10px solid black;
    border-bottom: 5px solid transparent;
}
<div data-tooltip="I am Nancy Moore">
	<label>Name</label>
</div>

答案 1 :(得分:1)

你是说那个吗?

body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

label {
    position: relative;
    white-space: nowrap;
}

label:hover::before {
    content: attr(data-tooltip);
    bottom: calc(100% + 10px);
    left: 50%;
    position: absolute;
    padding: 5px 10px;
    background: black;
    color: white;
    border-radius: 3px;
    transform: translate(-50%, 0);
}

label:hover::after {
    content: '';
    top: -10px;
    left: 50%;
    position: absolute;
    border-top: 5px solid #000;
    border-right: 5px solid transparent;
    border-bottom: 5px solid transparent;
    border-left: 5px solid transparent;
    transform: translate(-50%, 0);
}
<label data-tooltip="I am Nancy Moore">Name</label>

答案 2 :(得分:0)

<style>
    .tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
}

.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -60px;
  opacity: 0;
  transition: opacity 0.3s;
}

.tooltip .tooltiptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
  opacity: 1;
}
    </style>



  <div class="tooltip"> <label>Name</label>
  <span class="tooltiptext">I am Nancy Moore</span>
</div>