我可以设置一个元素的大小来适应它的潜在内容,而不是它的实际内容吗?

Can I set an element's size to fit its potential content, rather than its actual content?

考虑一下这个按钮栏:

body {text-align: right;}
<button>Save</button>
<button>Cancel</button>
<button>Delete</button>

现在假设最后一个按钮的内容发生变化:

body {text-align: right;}
<button>Save</button>
<button>Cancel</button>
<button>Click me again to confirm deletion</button>

如您所见,最右侧按钮的这一变化触发了其左侧的所有按钮移动。

为避免这种情况,我希望按钮的原始大小适合其两个可能内容中较大的一个。

当然,我可以通过多种方式尝试"achieve"。最简单也是最丑陋的就是试验较大的内容需要多少宽度然后"hardcode"它:

body {text-align: right;}

#del {display: inline-block; width: 220px;}
<button>Save</button>
<button>Cancel</button>
<button id="del">Delete</button>

但是,我认为它不是解决方案,因为不能保证此宽度对其他所有人都相同。如果有人使用奇怪的字体,或者使用文本放大,或者在移动设备上查看网站,或者其他什么,那么我想将按钮的宽度设置为硬编码值可能会产生奇怪的结果。

我想,另一种方法是 (a) 首先将较长的文本放入按钮 (b) 通过 JavaScript 获取按钮的宽度并保存 (c) 放入实际的较短文本到按钮并将其宽度设置为该值。然而,根据我的直觉,这看起来像是一个可怕的黑客和矫枉过正。

解决此类问题的规范方法是什么?

我会考虑使用数据属性添加两个使用伪元素的文本,然后将不透明度控制为 hide/show 它们:

div {
  text-align: right;
}

#del {
  display: inline-block;
  position: relative
}

#del:before {
  content: attr(data-text);
  position:absolute;
  left:0;
  right:0;
  top:1px; /*there is 1px default padding */
  text-align:center;
}

#del:after {
  content: attr(data-alt);
  opacity:0;
}


#del:hover::before {
   opacity:0;
}
#del:hover::after {
   opacity:1;
}
<div><button>Save</button><button>Cancel</button><button data-text="Delete" data-alt="Click me again to confirm deletion" id="del"></button></div>

您只需要知道哪一个会更宽,以使其流入以定义宽度并制作另一个 position:absolute

你也可以把正文放在里面:

div {
  text-align: right;
  font-size:14px;
}

#del {
  display: inline-block;
  position: relative;
}

#del span {
  content: attr(data-text);
  position:absolute;
  left:0;
  right:0;
  top:1px; /*there is 1px default padding */
  text-align:center;
}

#del:after {
  content: attr(data-alt);
  opacity:0;
}


#del:hover span {
   opacity:0;
}
#del:hover::after {
   opacity:1;
}
<div><button>Save</button><button>Cancel</button><button  data-alt="Click me again to confirm deletion" id="del"><span>Delete</span></button></div>