Implement horizontal center positioning of div
P粉573809727
P粉573809727 2023-09-05 13:03:23
0
2
475
<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粉573809727
P粉573809727

reply all(2)
P粉659518294

You can center it horizontally by:

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

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template