Create the Tooltip Component in Vuejs

With 3 steps bellow you can create a Tooltip component to import to anywhere in your Vue App.

Step 1: Create a Vue component called Tooltip.vue and add the codes bellow:



<script>
export default {
  props: {
    position: String,
    content: String
  }
};
</script>


Step 2: Create a CSS file call styles.css with the CSS codes below and import to your tooltip component:

 .tooltip {
  position: relative;
  display: inline-block;
}
.tooltip .tooltip-text {
  visibility: hidden;
  width: 120px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  position: absolute;
  z-index: 1;
  opacity: 0;
  transition: opacity 0.3s;
}
/* Tooltip top content */
.top .tooltip-text {
  bottom: 100%;
  left: 50%;
  margin-left: -60px; /* 120/2 = 60 */
}
/* Tooltip right content */
.right .tooltip-text {
  top: -5px;
  left: 110%;
}
/* Tooltip bottom content */
.bottom .tooltip-text {
  top: 100%;
  left: 50%;
  margin-left: -60px; /* 120/2 = 60 */
}
/* Tooltip left content */
.left .tooltip-text {
  top: -5px;
  right: 110%;
}
.tooltip .tooltip-text::after {
  content: "";
  position: absolute;
  border-width: 5px;
  border-style: solid;
}
/* Tooltip top arrow */
.top .tooltip-text::after {
  margin-left: -5px;
  left: 50%;
  top: 100%;
  border-color: #555 transparent transparent transparent;
}
/* Tooltip bottom arrow */
.bottom .tooltip-text::after {
  margin-left: -5px;
  bottom: 100%;
  left: 50%;
  border-color: transparent transparent #555 transparent;
}
/* Tooltip left arrow */
.left .tooltip-text::after {
  top: 50%;
  margin-top: -5px;
  left: 100%;
  border-color: transparent transparent transparent #555;
}
/* Tooltip right arrow */
.right .tooltip-text::after {
  top: 50%;
  margin-top: -5px;
  right: 100%;
  border-color: transparent #555 transparent transparent;
}
.tooltip:hover .tooltip-text {
  visibility: visible;
  opacity: 1;
}


Step 3: Use in your Vue app like this


<script>
import Tooltip from "./components/Tooltip";
export default {
  name: "App",
  components: {
    Tooltip
  }
};
</script>


Note:
- In the example above, we use the position property is "top" that mean the tooltip content will be display on the top position of your element, you can change to "left", "right", "bottom".
- The content property of the Tooltip component is the content that you want to display inside tooltip.

Run your app and hover the mouse to your content to see the result like this:



Read more:
- React Tooltip Component
- Create CSS tooltip for all positions

cssjavascriptvue tooltipvuejs

© 2019 4codev

Created with love by Sil.