How to center a

element inside a

container?

前端 未结 7 852
旧巷少年郎
旧巷少年郎 2020-12-13 23:34

I want my

element to be at the center of a container

, as in perfectly centered -- the top, bottom, left and right margins spl
相关标签:
7条回答
  • 2020-12-14 00:18

    This solution works fine for all major browsers, except IE. So keep that in mind.

    In this example, basicaly I use positioning, horizontal and vertical transform for the UI element to center it.

            .container {
                /* set the the position to relative */
                position: relative;
                width: 30rem;
                height: 20rem;
                background-color: #2196F3;
            }
    
    
            .paragh {
                /* set the the position to absolute */
                position: absolute;
                /* set the the position of the helper container into the middle of its space */
                top: 50%;
                left: 50%;
                font-size: 30px;
                /* make sure padding and margin do not disturb the calculation of the center point */
                padding: 0;
                margin: 0;
                /* using centers for the transform */
                transform-origin: center center;
                /* calling calc() function for the calculation to move left and up the element from the center point */
                transform: translateX(calc((100% / 2) * (-1))) translateY(calc((100% / 2) * (-1)));
            }
    <div class="container">
        <p class="paragh">Text</p>
    </div>

    I hope this help.

    0 讨论(0)
提交回复
热议问题