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

怎甘沉沦 提交于 2019-12-23 19:29:49

问题


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);

回答1:


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;
}



回答2:


if you give float to the div then margin:auto not works.So,auto & float is not simultaneously work.




回答3:


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>


来源:https://stackoverflow.com/questions/4705105/center-multiple-variable-length-divs-within-a-parent-div-in-css

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!