Why is is top:50% in css not working?

后端 未结 7 1683
野性不改
野性不改 2021-02-03 22:30

I am making a website and I\'m trying to vertically center:

 position: absolute;
 width:1200px;
 height:600px;
 top: 50%;
 left: 50%;
 margin-left: -600px;
         


        
7条回答
  •  被撕碎了的回忆
    2021-02-03 22:59

    To answer your question why top: 50% is not working, when you use property top on an element, the parent of that element needs to have a static height set in place. This should be in px or a unit other than percent. If you really need to use percent in your parent as well, then you can move on to the next parent (which is the parent of that parent) and have that one a fixed static height.

    To vertically centering anything. I prefer to use this method

    The use of CSS transform since you don't have to know what the width of height your element has.

    position: relative;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    

    Don't forget to add browser/vendor prefixes.

    You can refer here for vendor prefixes.


    If you don't know the height of your parent. You have two options:

    1. Using JavaScript take the natural height of the parent element and then set the height property of that parent element to the value you just took. You can use this method when the height of the parent element is caused by another child element that is sibling to the element you are centering.

    $('.parent').height( $(this).height() );
    .parent {
      /* Unkown height */
    }
    
    .child {
      /* Create columns */
      width: 50%;
      float: left;
    }
    
    .child-1 {
      position: relative;
      top: 50%;
      text-align: center;
      -webkit-transform: translateY(-50%);
      -moz-transform: translateY(-50%);
      -ms-transform: translateY(-50%);
      -o-transform: translateY(-50%);
      transform: translateY(-50%);
    }
    
    
    
    
    Lorem ipsum
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    Tip: If you are taking responsive into concern, just set height again in JavaScript on browser resize. You can get the new natural height by setting height to auto in JavaScript and do the process again.

    1. You can scratch the ideas above and use centering with display: table instead. CSS-Tricks has a very good example here.

提交回复
热议问题