How to center a “position: absolute” element

后端 未结 26 3232
-上瘾入骨i
-上瘾入骨i 2020-11-21 05:35

I\'m having a problem centering an element that has the attribute position set to absolute. Does anyone know why the images are not centered?

<
相关标签:
26条回答
  • 2020-11-21 06:16

    The simpler, the best:

    img {
                top: 0;
                bottom: 0;
                left: 0;
                right: 0;
                margin: auto auto;
                position: absolute;
    }
    

    Then you need to insert your img tag into a tag that sports position:relative property, as follows:

    <div style="width:256px; height: 256px; position:relative;">
          <img src="photo.jpg"/>
    </div>
    
    0 讨论(0)
  • 2020-11-21 06:17

    Here is easy and best solution for center element with “position: absolute”

     body,html{
      min-height:100%;
     }
     
     div.center{
     width:200px;
     left:50%;
     margin-left:-100px;/*this is 50% value for width of the element*/
     position:absolute;
     background:#ffffd;
     border:1px solid #999;
     height:100px;
     text-align:center
     }
     
     
    <style>
    
    </style>
    
    <body>
     <div class='center'>
      should be centered verticaly
     </div>
    </body>

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