css inline-block elements, last child to float left when using text-align:center on parent div

StackOverflow https://stackoverflow.com/questions/20355721

  •  28-08-2022
  •  | 
  •  

Question

Here you have the code and demo version of the problem. if you see the last two black boxes are in center is there a way to make them show on left side ?

mainparent
{
  width:500px;
  height:200px;
  text-align:center;
  background:#ccc;
}
.boxes
{
  width:50px;
  height:50px;
  display:inline-block;
  margin-left:5px;
  background:#000;
}

DEMO

Was it helpful?

Solution

Why not just float them left ? (and resize your container to fit them..)

This way you have better control of the margins, since the font-size does not affect them (nor the whitespace)

#mainparent
{
    width:480px;
    height:200px;
    background:#ccc;
}
.boxes
{
    width:50px;
    height:50px;
    float:left;
    margin:5px;
    background:#000;
}

Demo at http://jsfiddle.net/JxhP8/32/


Update

If you want the elements left aligned amongst themselves but center aligned in their container, you will need another element in the middle and some javascript..

Here is a jquery implementation

html

<div id="mainparent">
    <div class="centerized">
        <div class="boxes"></div>
        <div class="boxes"></div>
        <div class="boxes"></div>
        ..
        ..
        <div class="boxes"></div>
        <div class="boxes"></div>
        <div class="boxes"></div>
    </div>
</div>

css

#mainparent
{
    background:#ccc;
}
.centerized{
    overflow:hidden; // to grow according to the boxes
    margin:0 auto; // to be centered in container
}

jquery

$(function(){
    // cache the repeatedly used elements
    // and fixed values
    var main = $('#mainparent'),
        centerized = main.find('.centerized'),
        itemWidth = main.find('.boxes').outerWidth(true);

    $(window).resize(function(){
        var fitItems = (main.width() / itemWidth) | 0;
        centerized.width(fitItems * itemWidth);
    }).trigger('resize');
});

Demo at http://jsfiddle.net/JxhP8/34/

OTHER TIPS

Change your CSS #mainparent text-align to left.

Since you already have answers, an alternative is to use CSS Selectors

#mainparent
{
    width:500px;
    height:200px;
    text-align:center;
    background:#ccc;
}
.boxes
{
    width:50px;
    height:50px;
    display:inline-block;
    margin-left:5px;
    background:#000;
}

.boxes:nth-child(17)
{float:left; margin-left:21px;}

.boxes:nth-child(18)
{float:left; margin-left:9px;}

JSFIDDLE

You still have work to do to get the layout correct, it only works when you have a fixed number of boxes etc, but you may find this approach useful (or horrible to know not to use it again!)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top