简体   繁体   中英

Center multiple variable-length divs within a parent div in CSS

I have three small divs that all appear within one parent div. The second (middle) div is variable size, as it will display text of slightly different lengths (month names).

How can I make the the centre div align to the centre of the parent div so that the first and third divs align correctly in the remaining space?

The CSS so far is here (but it doesn't work yet):

div.calendartitle {  //The parent
  display: block;
  width: 117px;
  height: 15px;
  border-style: solid;
  border-color: black;
  font-size: small;
  border-width: 1px;
  text-align: center;
}


div.calendartitleelement {  //The three sub-divs.
  display: block;
  float: left;
  margin-left: auto;
  margin-right: auto;
  width: 38px;
}

The HTML is generated in JS:

var html = "<div class='calendartitle'>";
  html += "<div class='calendartitleelement calendertitleclickable' onclick='buildCalendar(" + previousWeekStartingDay + "," + previousMonth + ");'>&#60;&#60;</div>";
  html += "<div class='calendartitleelement'>" + months[month] + "</div>";
  html += "<div class='calendartitleelement calendertitleclickable' onclick='buildCalendar(" + nextWeekStartingDay + "," + nextMonth + ");'>&#62;&#62;</div></div>";
  $("#calendardisplay").prepend(html);

如果你给浮点数div然后保证金:自动不工作。所以,自动和浮动不同时工作。

You should not use float left with centering properties such as margin auto. Do this.

div.calendartitleelement {  //The three sub-divs.
  display: block;
  margin:0px auto;
  min-width: 38px;
}

First put them in a wrapper div.

    <div class="wrapper">
<ul class="menu clearfix">
    <li class="item">test</li>
    <li class="item">test</li>
    <li class="item">test</li>
</ul>
</div>

<style>
.wrapper {
    text-align: center;
}

.wrapper .menu {
  display: inline-block;
  *display: inline; /* ie6/7 hack for display inline, haslayout property */
}

.wrapper .menu li {
  float: left;
}

.clearfix:after {
    content:".";
    display:block;
    height:0;
    clear:both;
    visibility:hidden;
}
.clearfix {display:inline-block;}
/* Hide from IE Mac \*/
.clearfix {display:block;}
/* End hide from IE Mac */
</style>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM