johann_ka February 2016

CSS - Top menu with horizontally centered one- and two-line-long entries – without flex?

I'm trying to build a top menu that horizontally centers a few entries that are one or two lines long using simple div and display:inline-table. The problem is that I haven't found a way to center the entries that are only one line long (Item0 and Item1), unless I use display:flex. I would like to do this without specifying the height in pixel.

The yellow boxes around the entries are just for reference, so that I can better see what is going on which each entry.

Since I'm very new to front-end development, I would like to know if there is a better way to do that.

Here is the jsbin.

Thanks! J

Answers


dippas February 2016

you can use display:table/table-cell see snippet below (I've simplified your code a bit):

Snippet

body {
  font-family: ubuntu;
}
#nav1 {
  width: 100%;
  background-color: grey;
  display: table
}
.menus {
  display: table-cell;
  vertical-align: middle;
  font-size: 0.9em;
  text-align: right;
  color: yellow;
  padding: 8px;
  border: solid 1px;
}
<div id="nav1">
  <div class="menus">
    Item 0 (1 line)
  </div>
  <div class="menus">
    Item 1 (1 line)
  </div>
  <div class="menus">
    Item 2 long text
    <br>item 2 long text
  </div>
  <div class="menus">
    Item 3 long text
    <br>item 3 long text
  </div>
  <div class="menus">
    Item 4 long text
    <br>item 4 long text production
  </div>
  <div class="menus">
    Item 5 long text
    <br>item 5 long text
  </div>
</div>

Post Status

Asked in February 2016
Viewed 1,908 times
Voted 6
Answered 1 times

Search




Leave an answer