Implement horizontal center positioning of div
P粉573809727
2023-09-05 13:03:23
<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>
You can center it horizontally by:
You can use the
display: flex;
property to center align the component.css flex