css vertically centering a fixed positioning div

前端 未结 7 890
醉酒成梦
醉酒成梦 2020-12-08 04:17

I have the following HTML for a sort-of lightbox project.

th

相关标签:
7条回答
  • 2020-12-08 04:29

    To vertically center an item you need the following 2 css attributes :

    display:table-cell;
    vertical-align:middle;
    

    example : http://jsfiddle.net/yjv94/

    0 讨论(0)
  • 2020-12-08 04:34

    The best solution I've seen for both vertically and horizontally centering a position: fixed div is:

    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    

    Fiddle and source. You don't need to know the dimensions of the div and it doesn't require any container divs. The centered div's width can even be a percentage (which was what I was looking for when I found this solution).

    0 讨论(0)
  • 2020-12-08 04:38

    Here are couple SASS mixins I'm using... I hope this is going to help someone:

    // vertically centers as relative
    @mixin vertical-align {
        position: relative;
        top: 50%;
        -webkit-transform: translateY(-50%);
        -ms-transform: translateY(-50%);
        transform: translateY(-50%);
    }
    
    
    // vertically centers the element as absolute
    @mixin vertical-center {
        position: absolute;
        top: 50%;
        -webkit-transform: translateY(-50%);
        -ms-transform: translateY(-50%);
        transform: translateY(-50%);
    }
    
    
    // horizontally centers the element as absolute
    @mixin horizontal-center {
        position: absolute;
        left: 50%;
        -webkit-transform: translateY(-50%);
        -ms-transform: translateY(-50%);
        transform: translateY(-50%);
    }
    
    
    // absolutely centers the element inside of its first non-static parent
    @mixin absolute-center {
        position: absolute;
        top: 50%;
        left: 50%;
        -webkit-transform: translateY(-50%);
        -ms-transform: translateY(-50%);
        transform: translateY(-50%);
    }
    
    0 讨论(0)
  • 2020-12-08 04:40

    If you want the image to have a fluid size, you can use the height of the view as a reference:

    #img {
       position: relative; /* or absolute or fixed depending on your needs */
       top: 50%;
       height: 80vh;
       margin-top: -40vh; /* minus half the height */
    }
    
    0 讨论(0)
  • 2020-12-08 04:41

    Alternatively, you could try this (only works if you know the height of the image):

    #image{
    position:relative;
    height:600px;
    top: 50%;
    margin-top: -300px; /* minus half the height */
    border:1px solid grey;
    }
    
    0 讨论(0)
  • 2020-12-08 04:41

    have you check this soution?:

    CSS: Vertically align div when no fixed size of the div is known

    here you dont need to have a height declared.

    Regards

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