简体   繁体   中英

centering a CSS div, having problems with the middle

http://codepen.io/willc86/pen/hpFLe

Hey guys I have a code pen link on top so you guys can see it. I am pretty much having problems centering the middle box. How do I do that. When I do center it, the middle box seems to favor one side when I zoom out of the browser

this is my code

#box{
  border: 3px solid red;

}

#space{
  text-align: center;

}
#leftcolumn { 
  width: 300px; border: 1px solid red; float: left; margin: 40px;
  margin-right: 20px;

}
#rightcolumn { 
  width: 300px; border: 1px solid red; float: right; 
  margin: 40px; margin-left: 20px;

}
#mcolumn {
   width: 300px; border: 1px solid red; float: left; margin: 40px;

}
.clear {
   clear: both;
}

and my HTML

<div id="box">
      <div id="space">       
            <div id="leftcolumn"><p>LEFT</p></div>
            <div id="rightcolumn"><p>RIGHT</p></div>
            <div id="mcolumn"><p>mcolomn</p></div>
            <div class="clear"></div>          
      </div>
  </div>

Middle block sticks to one side because of the "float: left" rule. To be centered it needs no float. You can just add 'auto' horizontal margin without any float and it will work fine.

Here is modified example: http://codepen.io/anon/pen/pitod

(there's a trick with top padding for parent container to avoid problems with top margins, but you can solve that however you like)

hope it will help you, #mcolumn is centered now

 #mcolumn {
 width: 300px;
 border: 1px solid red;
 margin: 40px auto;
 display: inline-block;
 }

Demo

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