Position by center point, rather than top-left point

后端 未结 6 2163
鱼传尺愫
鱼传尺愫 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:20

    If the element must be absolutely positioned (so, margin: 0 auto; is of no use for centering), and scripting is out of the question, you could achieve this with CSS3 transforms.

    .centered-block {
        width: 100px; 
        left: 50%; 
        -webkit-transform: translate(-50%, 0); 
        position: absolute;
    }
    

    See this fiddle for some examples. The important parts: left: 50%; pushes block halfway across its parent (so its left side is on the 50% mark, as you mentioned). transform: translate(-50%, 0); pulls the block half it's own width back along the x-axis (ie. to the left), which will place it right in the center of the parent.

    Note that this is unlikely to be cross-browser compatible, and will still require a fall back of some sort for old browsers.

提交回复
热议问题