Centering responsive DIVs within a container

2020-03-30 07:08发布

问题:

If you resize the screen the divs are responsive and move. When the right hand div drops below, it leaves space to the right of the screen. I want all the divs to automatically center instead of staying to the left

I created this JSFiddler to help explain but it doesn't allow me to post with message. Will post below.

Any help?

回答1:

Using floats and centering is very difficult. Try using display:inline-block instead and add text-align:center on the wrapping parent.

JSfiddle Demo

Amended CSS

#wrapper {
    max-width: 900px;
    margin: 0 auto;
    text-align:center; /* add this */
}

.box-container { 
    background: none repeat scroll 0 0 #FFFFFF;
    //float: left; /*tremove this */
    display: inline-block; /* add this */
    margin: 50px 5px 50px;
    overflow: hidden;
    position: relative;
    width: 185px;
    box-shadow: 0px 0px 5px #BBBBBB;
    text-align:center;
    text-decoration: none;

}