Howdy_McGee
Howdy_McGee

Reputation: 10635

Center Grid Based on Device Width

I have a Grid (on my screen, 2 rows: 4 boxes and 1 box) that I want to center on the screen based on the width of the screen. No matter if there's 4 boxes or 2 boxes in the first row it should be centered in the screen.

I know I can achieve this with javascript but my question is - is this achievable in CSS?

I have some very simple code and a JSFiddle:

HTML

<div id="container">
    <ul>
        <li></li>
        <li></li>
        <li></li>       
        <li></li>
        <li></li>
    </ul>
</div>

CSS

*{
    margin: 0px;
    padding: 0px;
}

#container{
    width: 93%;
    margin: 0 auto;
}

ul{
    list-style-type: none;
    margin-top: 10px;
    margin-left: 10px;
}

ul li{
    border: 1px solid black;
    width: 300px;
    height: 300px;
    float: left;
    margin-right: 10px;
    margin-bottom: 10px;
}

Upvotes: 1

Views: 57

Answers (2)

Ivan Chernykh
Ivan Chernykh

Reputation: 42166

Vanilla CSS solution, http://jsfiddle.net/MUaHz/3/ :

*{
    margin: 0px;
    padding: 0px;
}

#container{
    width: 93%;
    margin: 0 auto;
    border: 1px solid #009900;
}

ul{
    list-style-type: none;
    margin-top: 10px;

    margin: 0 auto;
    border: 1px solid #000099;
    text-align: center;
}

ul li{
    border: 1px solid black;
    width: 300px;
    height: 300px;
    display: inline-block;
    margin-right: 10px;
    margin-bottom: 10px;
}

Upvotes: 2

Mahmoude Elghandour
Mahmoude Elghandour

Reputation: 2931

You Can Use This

#container{
position: fixed; top: 50%; left: 50%; width: 93%; height: 200px;
}
ul li{
position: relative; top: -50%; left: -50%; width: 100%; 
height: 100%; background-color:red; color: white;
margin-bottom: 5px;
border: 1px solid black;
}

http://jsfiddle.net/modaloda/MUaHz/2/

See This Link : Link

Upvotes: 1

Related Questions