Search code examples
htmlcssangularangular-content-projection

dynamically change div shape and size based on its content


I have a div element which should be exactly the same shape and size of its icon content. I'm designing a component in Angular 9 which is a button that navigates you to the previous page. I want this component to be reusable, so the icon element inside it must be changeable. I easily achieve this through Angular's content projection, but the problem is that the div outer container is actually bigger than its content, resulting in the icon area being overflown by the real "clickable" area.

This is the html page

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

Without content-projection, the html page would look like this (I think my problem is beyond Angular content projection)

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

display: inline-block, as suggested here, doesn't work.


Solution

  • As for css - test how to fix it

    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 */
    }
    

    Finally use Validator w3c


    update
    I assume icon means image, best practise is to set the fixed size, because browser doesn't need guess and doesn't jump when loading.
    If its size changes

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

    If for any reason the size is unpredictable - let it jump :)

    One more thing - if there's any float or flex, well, it might not be that easy.