代码之家  ›  专栏  ›  技术社区  ›  P. Nick

如何获得最大内容宽度值的一半?

  •  0
  • P. Nick  · 技术社区  · 6 年前

    我在想也许我可以用 calc() 具有 max-content 但显然这不是它的工作方式。

    *[tooltip] {
        position: relative;
        &:hover {
            &:after {
                content: attr(tooltip);
                display: block;
                position: absolute;
                transform: translateX(-50%);
                background: rgba(0, 0, 0, 0.8);
                color: white;
                padding: 6px 12px;
                border-radius: 4px;
                position: absolute;
                top: 50px;
                left: 0px;
                width: max-content;
                font-weight:bold;
                font-size:0.9em;
                text-align:center;
                margin-left: calc(max-content / 2);
            }
        }
    }
    

    我总是可以使用100%作为宽度,但它总是父对象的宽度,有时太小,有时太多;因此我使用 最大含量 .

    <div tooltip="Hello World">Hover me.</div>
    

    不使用JS

    编辑:

    这是它应该是什么样子的图像。

    enter image description here

    使用“最大内容”时,宽度总是与其他工具提示不同,这就是为什么我很难将其居中的原因。

    2 回复  |  直到 6 年前
        1
  •  3
  •   Paulie_D    6 年前

    使用 transform

      *[tooltip] {
            position: relative;
            &:hover {
                &:after {
                    content: attr(tooltip);
                    display: block;
                    position: absolute;
                    background: rgba(0, 0, 0, 0.8);
                    color: white;
                    padding: 6px 12px;
                    border-radius: 4px;
                    position: absolute;
                    top: 50px;
                    /* this */
                    left:50%; 
                    transform:translateX(-50%);
    
                    width: max-content;
                    font-weight:bold;
                    font-size:0.9em;
                    text-align:center;
                 }
            }
        }
    
        2
  •  0
  •   NicossB    6 年前

    有个办法

    .parent {
      display: inline-block;
    }
    
    *[tooltip] {
      position: relative;
    }
    
    *[tooltip]:hover:after {
      content: attr(tooltip);
      background: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 6px 12px;
      border-radius: 4px;
      display: table-cell;
      position: absolute;
      overflow: hidden;
      white-space: nowrap;
      left:50%; 
      transform:translateX(-50%);
    }
    <div tooltip="Hello World" class="parent">Hover me.</div>