Salim Hossain Salim Hossain - 1 month ago 16
HTML Question

absolute position centering with transform having issues

I have some list items to be centered. I must do it with position absolute as it overlaps another div. I can do it with position and transform properties. But it has a problem when the device width is smaller. I want it to be centered as much long as possible, but it breaks before the device width is enough smaller. I can fix it using calc, but what to do when the ul width is unknown?


codepen



.parent {
height: 70px;
margin-top: 100px;
width: 100%;
background: #000;
position: relative;
}

ul,li {
list-style-type: none;
}

ul {
position: absolute;
bottom: 0;
margin: 0;
padding: 0;
top: 0;
left: 50%;
transform: translate(-50% , 0);
clear:both;
display:block;
}

li {
height: 70px;
width: 70px;
background: #f44;
display: inline-block;
border-radius: 50%;
margin-left: 10px;
margin-right: 10px;
margin-top: 0;
margin-bottom: 0;
}

<div class="parent">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>




Answer

Update your ul rule like this, where the left: 0/right: 0 will make it full width and text-align center the li's

ul {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  padding: 0;
  margin: 0;
  text-align: center
}

Sample snippet

.parent {
  height: 70px;
  margin-top: 100px;
  width: 100%;
  background: #000;
  position: relative;
}

ul,li {
  list-style-type: none;
}

ul {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  padding: 0;
  margin: 0;
  text-align: center
}

li {
  height: 70px;
  width: 70px;
  background: #f44;
  display: inline-block;
  border-radius: 50%;
  margin-left: 10px;
  margin-right: 10px;
  margin-top: 0;
  margin-bottom: 0;
}
<div class="parent">
  <ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
  </ul>
</div>