0

I want to position a div at the center of the screen. The issue is when the div is small, from left 45% looks fine but when the div is longer(ie more width), I need to make it from left 30%

Is there a smart way to position the div at the center based on the size of div.

body {
background:blue;
}

.box  {
position: absolute;
top:10px;
left:30%;
background:white;
padding:10px;
border-radius:10px;
}
<div class="box">
This is long div so need left = 30 percent
</div>
Tomaz_
  • 349
  • 2
  • 11

3 Answers3

2

You can align center the component using display: flex; attribute.

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">
This is long div so need left = 30 percent
</div>
ChanHyeok-Im
  • 541
  • 3
  • 11
1

You can center it horizontally that way:

.box  {
   position: absolute;
   top:10px;
   left:50%;
   background:white;
   padding:10px;
   border-radius:10px;
   transform: translateX(-50%);
}
Mohammed Ahmed
  • 435
  • 2
  • 11
1

to center a div horizontally, a simple solution is to set its margin to "auto":

body {
background:blue;
}

.box  {
width: fit-content;
margin: auto;
background:white;
padding:10px;
border-radius:10px;
}