How to center a “position: absolute” element

后端 未结 26 3247
-上瘾入骨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:14

    Your images are not centered because your list items are not centered; only their text is centered. You can achieve the positioning you want by either centering the entire list or centering the images within the list.

    A revised version of your code can be found at the bottom. In my revision I center both the list and the images within it.

    The truth is you cannot center an element that has a position set to absolute.

    But this behavior can be imitated!

    Note: These instructions will work with any DOM block element, not just img.

    1. Surround your image with a div or other tag (in your case a li).

      my-image

      Note: The names given to these elements are not special.

    2. Alter your css or scss to give the div absolute positioning and your image centered.

      .absolute-div {
        position: absolute;
      
        width: 100%; 
        // Range to be centered over. 
      
        // If this element's parent is the body then 100% = the window's width
      
        // Note: You can apply additional top/bottom and left/right attributes
        // i.e. - top: 200px; left: 200px;
      
        // Test for desired positioning.
      }
      
      .absolute-div img {
        width: 500px;
        // Note: Setting a width is crucial for margin: auto to work.
      
        margin: 0 auto;
      }
      

    And there you have it! Your img should be centered!

    Your code:

    Try this out:

    body
    {
      text-align : center;
    }
    
    #slideshow
    {
      list-style : none;
      width      : 800px;
      // alter to taste
    
      margin     : 50px auto 0;
    }
    
    #slideshow li
    {
      position : absolute;
    }
    
    #slideshow img
    {
      border  : 1px solid #CCC;
      padding : 4px;
      height  : 500px;
      width   : auto;
      // This sets the width relative to your set height.
    
      // Setting a width is required for the margin auto attribute below. 
    
      margin  : 0 auto;
    }
    • Dummy 1
    • Dummy 2

    I hope this was helpful. Good luck!

提交回复
热议问题