Position by center point, rather than top-left point

后端 未结 6 2086
鱼传尺愫
鱼传尺愫 2021-02-01 01:14

Is it possible to tell the code to position by the center point of an element, rather than by the top-left point? If my parent element has

width         


        
6条回答
  •  余生分开走
    2021-02-01 01:38

    Stumbled upon this question, and I'd like to add another way to center content within a div.

    By using the CSS3 display mode 'flexible box', as in setting the following CSS properties to the parent div

    display: flex;
    position: relative;
    align-items: center;
    justify-content:center;
    

    And 'at least' setting the following properties to the child div

    position:relative;
    

    The browser will automatically center the contents within the parent div, unaffected by their width or height, this particularly comes in handy when you're developing something like an image grid or just want to remove the hassle of calculating a divs position, then having to recalculate it when you change your mind about the set-up of said div.

    In my own work, I tend to set-up a class named

    .center-center
    

    With the properties I described for the parent div, then just add it to whatever element of which I need its contents centered.

    I've created a JSFiddle to support this explanation, feel free to click on the red squares to see the positioning in action.

    https://jsfiddle.net/f1Lfqrfs/

    For multi-line support, you can add (or uncomment in the JSF) the following CSS property to the parent DIV

    flex-wrap: wrap;
    

提交回复
热议问题