Ωmega
Ωmega

Reputation: 43703

Unwanted center alignment

I need to list several sections of div that has display parameter inline-block. As a group, I need them to be centered on screen, but I wish them to start on left of such group when a "new line" is needed.

Here is a very simple demonstration: https://jsfiddle.net/fcdm56ra/

div.c1 {
  background: #fff;
  display: inline-block;
  text-align: center;
}

div.c2 {
  display: inline;
  text-align: left;
  align: left;
}

div.c3 {
  border-color: #0f0;
  border-style: solid;
  border-width: 3px;
  display: inline-block;
  margin: 5px;
  vertical-align: top;
}
<div class="c1">
  <div class="c2">
    <div class="c3">
      111111111111111111<br>abc
    </div>
    <div class="c3">
      22222222222222222
    </div>
    <div class="c3">
      3333333333333333
    </div>
    <div class="c3">
      444444444444444
    </div>
    <div class="c3">
      55555555555555
    </div>
    <div class="c3">
      6666666666666
    </div>
    <div class="c3">
      777777777777<br>def
    </div>
  </div>
</div>

It looks like this:

enter image description here

...but I would like to have it as the following:

enter image description here

And even more ideal result would be to have it displayed like this:

enter image description here

...where the height of the "22222222222222222" block was autosized to its line height, to match height of other element(s) in the same "row".


Important part is that as a whole block it has to be centered on the screen and the c3 class has to be inline-block.

What is wrong in my code?

Upvotes: 0

Views: 57

Answers (2)

Jon
Jon

Reputation: 54

You could use flexbox here and a couple defined max widths to achieve this result:

div.c1 {
    background: #fff;
    display: flex;
    flex-wrap: wrap;
    margin: 0 auto;
    max-width: 38ch;
}
div.c3 {
    border-color: #0f0;
    border-style: solid;
    border-width: 3px;
    margin: 5px;
    max-width: 18ch;
    vertical-align: top;
}

Example: https://jsfiddle.net/pL2hog73/10/

UPDATE

Since you don't want to use Max-Widths you can try a grid approach. It doesn't exactly match your preferred output since the columns are a little more rigid.

div.c1 {
    background: #fff;
    display: grid;
    margin: 0 auto;
    width: 50%;
}
div.c3 {
    border-color: #0f0;
    border-style: solid;
    border-width: 3px;
    grid-column: 1;
    margin: 5px;
    vertical-align: top;
    width: min-content;
}

div.c3:nth-child(even) {
    grid-column: 2;
}

https://jsfiddle.net/f1jt845a/1/

Alternatively you could also just let the .c3 divs be width: min-content; display: inline and just insert a <br/> after every two. This would give you the left alignment you want without having to deal with grid/flexbox.

Upvotes: 1

Miro
Miro

Reputation: 8660

You should have the parent c2 as inline-block also:

div.c2 {
    display: inline-block;
    text-align: left;
}

Upvotes: 0

Related Questions