Page 96 - CSS
P. 96

Ghost element technique (Michał Czernow's hack)


        This technique works even when the container's dimensions are unknown.

        Set up a "ghost" element inside the container to be centered that is 100% height, then use
        vertical-align: middle on both that and the element to be centered.


        CSS


         /* This parent can be any width and height */
         .block {
           text-align: center;

           /* May want to do this if there is risk the container may be narrower than the element
         inside */
           white-space: nowrap;
         }

         /* The ghost element */
         .block:before {
           content: '';
           display: inline-block;
           height: 100%;
           vertical-align: middle;

           /* There is a gap between ghost element and .centered,
           caused by space character rendered. Could be eliminated by
           nudging .centered (nudge distance depends on font family),
           or by zeroing font-size in .parent and resetting it back
           (probably to 1rem) in .centered. */
           margin-right: -0.25em;
         }

         /* The element to be centered, can also be of any width and height */
         .centered {
           display: inline-block;
           vertical-align: middle;
           width: 300px;
           white-space: normal; /* Resetting inherited nowrap behavior */
         }


        HTML


         <div class="block">
           <div class="centered"></div>
         </div>


        Using text-align


        The most common and easiest type of centering is that of lines of text in an element. CSS has the
        rule text-align: center for this purpose:


        HTML






        https://riptutorial.com/                                                                               74
   91   92   93   94   95   96   97   98   99   100   101