Absolute center a fluid div

前端 未结 3 1668
独厮守ぢ
独厮守ぢ 2021-01-23 07:45

Good day.

I know that if you want to absolute center a div, you do this:

blahblah
相关标签:
3条回答
  • 2021-01-23 08:11

    This can be done with CSS alone.

    #parent {
      position: absolute;
      max-width: 500px;
      max-height: 500px;
      width: 100%;
      height: 100%;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    

    See demo https://jsfiddle.net/matharden/8kmvt8qd/

    0 讨论(0)
  • 2021-01-23 08:15

    As the width and height are fluid, you need to go with javascript or jQuery. Just add the below code in head tag. (The below example is in javascript)

    <script>
       window.onresize = function(){
          //To work even on resize
          getToMiddle();
       }
       window.onload = function(){
          getToMiddle();
       }
    
       function getToMiddle(){
          var box = document.getElementById('parent');
          var height = box.offsetHeight;
          var width = box.offsetWidth;
          box.style.top = -(height/2);
          box.style.left = -(width/2);
       }
    </script>
    

    and your css would be something like this:

    #parent{
       max-width: 500px;
       max-height: 500px;
       background-color:green;
       position:absolute;
       top: 50%;
       left: 50%;
      /* width: 10%;
       height: 10%; */
    }
    

    To test, give width: 10%; and height: 10%

    Working Fiddle

    0 讨论(0)
  • 2021-01-23 08:22

    I'll simply use flex to achieve this...

    #parent {
      display: flex;
      justify-content: center;
    }
    <div id="parent">
      <div id="child">blahblah</div>
    </div>

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