Home > Net >  How to use css property attr here?
How to use css property attr here?

Time:12-16

I have next realized tooltips (see snippet code).

body
{
    font-family: 'Arial', sans-serif;
    line-height: 1;

    min-height: 100vh;

    display: flex;
    justify-content: center;
    align-items: center;
}

*,
*:before,
*:after
{
    box-sizing: border-box;

    margin: 0;
    padding: 0;
}

.button
{
    position: relative;
    cursor: pointer;
    border: none;
    text-transform: uppercase;

    font-family: 'Montserrat', sans-serif;

    color: #fff;
    background-color: #21262b;

    border-radius: 5px;
    padding: 10px;

    font-weight: 700;
}

.button {
    margin: 0 10px;
}

.button::after {
    position: absolute;
    content: attr(data-tooltip);
    background: #21262b;
    padding: 5px;
    white-space: nowrap;
    border-radius: 5px;
    font-weight: 400;
    text-transform: none;
    min-width: 50px;

    left: 50%;
    top: -100%;
    transform: translateX(-50%);
}

.button::before {
    content: "";
    width: 10px;
    height: 10px;
    background: #21262b;
    position: absolute;
    top: -50%;
    left: 50%;
    transform: rotate(45deg) translate(0, 50%);
}

.button::before,
.button::after {
    opacity: 0;
}

.button:hover::before,
.button:hover::after {
    opacity: 1;
}
<button data-tooltip="Lorem Ipsum" >Tooltip Button</button>
<button data-tooltip="Lorem Ipsum" >Tooltip Button</button>
<button data-tooltip="Lorem Ipsum" >Tooltip Button</button>
<button data-tooltip="Lorem Ipsum" >Tooltip Button</button>

I want to add an additional data attribute for each button. Let me say it would be data-tooltip-left, data-tooltip-bottom, data-tooltip-top, data-tooltip-right. And for separate pseudo element after i want to change position. Or i just should remove general attribute data-tooltip? And for each of data-tooltip-position applying same styles but different position.

CodePudding user response:

/try using this way/

a:after {
  content: " (" attr(href) ")";
}

/this link might help you as well/

https://developer.mozilla.org/en-US/docs/Web/CSS/attr()

CodePudding user response:

Use attribute selectors.

In your case, you can set position like this data-tooltip-position="bottom".
The only one position attribute is enough, to prevent mistake for multiple position like this data-tooltip-bottom="" data-tooltip-top="". They are opposite positions.
For more combine position you can use data-tooltip-position="bottomleft".

Example:

<button data-tooltip="Lorem Ipsum" >Tooltip Button</button>
<button data-tooltip="Lorem Ipsum bottom"  data-tooltip-position="bottom">Tooltip Button</button>

In CSS, use selector like this.

.button[data-tooltip-position="bottom"]::after {
    top: auto;
    bottom: -100%;
}
.button[data-tooltip-position="bottom"]::before {
    top: 100%;
    transform: rotate(45deg) translate(0, 100%);
}

See it in action

  • Related