Karl Nickel
Karl Nickel

Reputation: 198

Centering floating elements

Currently I have the following code...

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <meta charset="UTF-8" />
    <link href="verna.css" type="text/css" rel="stylesheet" />
  </head>
  <body>
  <section id="devices">
    <h1>Gruppen</h1>
    <div class="group">
      <h2>Gruppe 1</h2>
      <ul>
        <li class="device">Schalter 1</li>
        <li class="device">Schalter 2</li>
        <li class="device">Schalter 3</li>
      </ul>
    </div>
    <div class="group">
      <h2>Gruppe 2</h2>
      <ul>
        <li class="device">Schalter 1</li>
        <li class="device">Schalter 2</li>
        <li class="device">Schalter 3</li>
      </ul>
    </div>
  </section>
  </body>
</html>

* {
    margin: 0;
    padding: 0;
}

ul {
    list-style-type: none;
}

#devices {
    background-color: yellow;
}

#devices .group {
    background-color: gray;
}

#devices .group ul {
    text-align: center;
}

#devices .group .device {
    background-color: green;
    display: inline-block;
    margin: 5px;
    max-width: 200px;
    width: 100%;
}

... which looks like this: enter image description here

But I want that the green <li>-elements floats in columns. It should look like this: enter image description here

Please note: The number of the green <li>-elements is variable, there can be more or less than three elements and there can be more than two columns! I want to order the <li>-elements "column-wise" and center them...

Thanks for help :-)

Upvotes: 4

Views: 216

Answers (3)

KatieK
KatieK

Reputation: 13863

Check out this fiddle.

The trick was to turn the lis back into block-level elements so that they could have width. Then set width: 40%; (40% leaves a little room for the 5px margin) and float: left;. Also adding overflow: auto; to the ul so that it would contain its floated lis.

Upvotes: 0

Andy
Andy

Reputation: 14575

The thing that is centering "Schalter 3" is text-align: center;. We can fix this by removing

#devices .group ul {
    text-align: center;
}

and adding:

#devices .group ul {
    margin-left: 50px;
}

#devices .group li {
    text-align: center;
}

in its place. This centers the text in the li element, instead of centering the li element inside the ul. And it adds the margin to the left to get the indent you wanted.

Working Fiddle.

Upvotes: 4

Kyros
Kyros

Reputation: 512

Restructure your html so that each "column" is it's own container (div) which has an appropriate width. Alternatively, if you hate yourself, use a table.

Upvotes: 0

Related Questions