htmlcssdrop-down-menuparent-childcenter-align

How to center sub-item of drop-down menu to parent?


I am trying to create a drop-down menu in which the children are center-aligned compared to the parent.

I have already tried setting margin: auto; or setting left: -50%; right: -50% along with other solutions I found online, but nothing seems to work for me.

How can I achieve that?

.header {
  /*background-image: url("../images/top_menu.png");*/
  width: 100%;
  background-repeat: no-repeat;
  background-position: left top;
  background-attachment: fixed;
  position: fixed;
  top: 0;
  background-origin: border-box;
  height: 68px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding-left: 5%;
  padding-top: 15px;
  padding-bottom: 10px;
  overflow: hidden;
  display: inline-block;
}

li {
  float: left;
}

li a,
.dropbtn {
  display: inline-block;
  color: #000;
  text-align: center;
  padding: 8px 10px;
  text-decoration: none;
  background-color: #fff;
  margin: 5px;
  border-radius: 30px;
  min-width: 160px;
}

li a:hover,
.dropdown:hover .dropbtn {
  background-color: black;
  color: white;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  min-width: 160px;
  text-align: center;
}

.dropdown-content a {
  color: #e6e6e6;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: center;
  background-color: #333333;
}

.dropdown-content a:hover {
  background-color: #e6e6e6;
  color: #333333;
}

.dropdown:hover .dropdown-content {
  display: block;
}
<div class="header">
  <ul class="drop_menu">
    <li class="dropdown">
      <a href='#' class="dropbtn">Products</a>
      <div class="dropdown-content">
        <a href='auto_tender_commercial.html'>Link 1</a>
        <a href='fruit_series.html'>Link 2</a>
        <a href='smart_sensors.html'>Link 3</a>
      </div>
    </li>
    <li class="dropdown">
      <a href='#' class="dropbtn">Bar Service Packages</a>
      <div class="dropdown-content">
        <a href='what_is_it.html'>Really long long long long long long long link</a>
        <a href='what_is_it.html'>Link 4</a>
        <a href='leasing_plan.html'>Link 5</a>
      </div>
    </li>
    <li><a href='event_leasing.html'>Event Leasing</a></li>
  </ul>
</div>

View on JSFiddle


Solution

  • In the comments it was suggested that jQuery could be an option.

    $(".dropdown-content").each(function() {
        $(this).css({
           'left' : '50%',
           'margin-left' : $(this).width() / 2 * - 1 + 'px'
        });
    });
    

    Here is my Fiddle: https://jsfiddle.net/pg60qetq/3/

    I had to change up the CSS slightly. I changed the postion from the DIV to the UL, removed some problematic height and overflow properties.

    Hope this helps.