Home  >  Q&A  >  body text

Implement horizontal center positioning of div

<p>I want to position a div in the center of the screen. The problem is that when the div is small, 45% from the left looks fine, but when the div is longer (i.e. wider in width), I need to change it to 30% from the left. </p> <p>Is there a smart way to position a div in the center based on its size. </p> <p> <pre class="brush:css;toolbar:false;">body { background:blue; } .box { position: absolute; top:10px; left:30%; background:white; padding:10px; border-radius:10px; }</pre> <pre class="brush:html;toolbar:false;"><div class="box"> This is a long div, so left = 30% is needed </div></pre> </p>
P粉573809727P粉573809727380 days ago428

reply all(2)I'll reply

  • P粉659518294

    P粉6595182942023-09-06 11:48:07

    You can center it horizontally by:

    .box  {
       position: absolute;
       top:10px;
       left:50%;
       background:white;
       padding:10px;
       border-radius:10px;
       transform: translateX(-50%);
    }

    reply
    0
  • P粉752290033

    P粉7522900332023-09-06 09:49:47

    You can use the display: flex;property to center align the component.

    css flex

    body {
    flex: 1;
    background:blue;
    display: flex;
    justify-content: center;
    }
    
    .box  {
    position: absolute;
    top:10px;
    background:white;
    padding:10px;
    border-radius:10px;
    }
    <div class="box">
    这是一个很长的div,所以需要左边=30%
    </div>

    reply
    0
  • Cancelreply