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

时间:2018-08-16 15:33:44

标签: css less

我正在显示一个工具提示,并且无论它有多长,我都希望它在父项中居中。

我当时在想,也许可以将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); } } } 一起使用,但是显然这不是它的工作原理。

max-content

我总是可以使用100%作为宽度,但是它始终是父级的宽度,有时太小而有时又太大了。因此我使用<div tooltip="Hello World">Hover me.</div>

$text = "The dog is saying wooff wooff wooff wooff but he should say 
bark bark bark bark not wooff wooff wooff";

$newText = preg_replace('!\wooff+', 'wooff{$total}', $text);

如何不使用JS 解决这个难题?

编辑:

这是它的外观图像。

enter image description here

无论工具提示中有多少文本,都应始终将其居中居中。如果我使用100%宽度的方法,它将保留在中间,但始终保持相同的宽度,从而导致单词分解为新的行。

通过使用max-content,宽度总是与其他工具提示不同,这就是为什么我很难将其居中。

2 个答案:

答案 0 :(得分:3)

使用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;
             }
        }
    }

答案 1 :(得分:0)

这是一种方法

.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>

相关问题