开发者

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

开发者 https://www.devze.com 2023-02-04 18:59 出处:网络
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).

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


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


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号