Home >Web Front-end >CSS Tutorial >Why Does My Horizontally Centered Triangle Pointer Shift During Resizing?
Problem Statement
The user intends to horizontally center a triangle pointer within a container element. While successful in certain window sizes, the pointer shifts out of alignment when the window is resized.
Solution
Understanding the Issue:
The initial attempt to center the pointer with left: 48% positions the pointer based on its left edge. This approach does not account for the element's width, resulting in misalignment when the window size changes.
Using transform to Achieve Centering:
To properly center the triangle, it's recommended to use the transform property:
.triangle { position: absolute; left: 50%; transform: translate(-50%,0); }
This rule shifts the triangle's position by 50% of its width, effectively centering it within the container.
Combining transform with Rotation:
In this specific scenario, the triangle element also has a transform: rotate(45deg) applied. However, CSS cascade rules override the first transform with the second, preventing the horizontal centering.
To address this, chain the transform functions:
.container::before { left: 50%; transform: translate(-50%,0) rotate(45deg); }
Multiple transform functions can be used together, applying in the order they are listed. In this case, translate is applied first, followed by rotate.
Complete Code Snippet:
body { background: #333333; } .container { width: 98%; height: 80px; line-height: 80px; position: relative; top: 20px; min-width: 250px; margin-top: 50px; } .container-decor { border: 4px solid #C2E1F5; color: #fff; font-family: times; font-size: 1.1em; background: #88B7D5; text-align: justify; } .container::before { top: -33px; left: 50%; transform: translate(-50%,0) rotate(45deg); position: absolute; border: solid #C2E1F5; border-width: 4px 0 0 4px; background: #88B7D5; content: ''; width: 56px; height: 56px; } <div class="container container-decor">great distance</div>
The above is the detailed content of Why Does My Horizontally Centered Triangle Pointer Shift During Resizing?. For more information, please follow other related articles on the PHP Chinese website!