根据其内容动态更改 div 形状和大小

dynamically change div shape and size based on its content

我有一个 div 元素,它的形状和大小应该与其 icon 内容完全相同。 我正在 component in Angular 9 中设计一个按钮,它可以将您导航到上一页。我希望这个组件是可重用的,所以它里面的图标元素必须是可变的。我通过 Angular 的 content projection 轻松实现了这一点,但问题是 div 外部容器实际上比它的内容大,导致图标区域被真正的“可点击”区域所淹没。

这是html页面

<div class="back-button-container clickable" (click)="navigateBack()">
    <ng-content select="[icon]"></ng-content>
</div>

如果没有内容投影,html 页面将如下所示(我认为我的问题超出了 Angular 内容投影)

<div class="back-button-container clickable" (click)="navigateBack()">
    <i icon class="far fa-2x fa-arrow-alt-circle-left" ></i>
</div>

display: inline-block,按照 here 的建议,不起作用。

至于css - 测试如何修复它

div{
height: auto;           /* it is by default - if wasn't changed not needed */ 
width: auto;            /* it is by default - if wasn't changed not needed */
padding: 0;             /* a space around the interior of the element*/
display: inline-block;  /* by default is block - takes up the full width */
}
i{
display: block;     /* takes up the full width of parent */
margin: 0;          /* you know what it is */
border: 0;          /* if you need border - set it, but don't let the user agent do it */
width: 120px;       /* not 120 but explicit how many px */
height: 120px       /* not 120 but explicit how many px */
}

终于使用Validatorw3c


更新
我假设图标是图像,最佳做法是设置固定大小,因为浏览器不需要猜测并且加载时不会跳转。
如果它的大小改变

i{
height: 100%;   /* or 10vh as 10% of devices screen */
width: auto;    /* if the image isn't square it won't be deformed */
}

如果由于任何原因无法预测大小 - 让它跳跃:)

还有一件事 - 如果有任何浮动或弹性,那么,它可能并不那么容易。