Centralize items of a DIV

Asked

Viewed 1,724 times

1

How do I keep these three items centered? Note that there is a space left on the right side.

inserir a descrição da imagem aqui

CSS

div.menu {
    background-color: #333;
    overflow: auto;
    white-space: nowrap;
}

div.menu a {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 15px;
    width: 30%;
    min-width: 30%;
    max-width: 30%;
    font-size: 110%;
    text-decoration: none;
}

div.menu a:hover {
    background-color: #777;
}

HTML

<div class="menu">
  <a href="#">Item 1</a>
  <a href="#">Item 2</a>
  <a href="#">Item 3</a>
</div>
  • Either I’m getting a little distracted or I can’t identify this space on the right side?

  • tries to split 100/number of links.

  • Centralizing LI or DIV will be the same, because the display:block|inline-block|table and float:left|right properties affect the behavior of almost all elements, just change the CSS selectors in the answer: http://answall.com/a/169088/3635 that already solves ;)

2 answers

1

You can use the calc CSS to calculate column size.

width: calc(100% / 3); /* Altera aqui */

min-width: 30%; /* Tira isso */ 
max-width: 30%; /* Tira isso */

0


How about just change the display to display: table of div and the tag a for display:table-cell;. To complete, place the width: 100% in div. That way besides not having space caused by padding, you leave something to add more items and it "adjust" the width for you.

See two examples below, one with 3 items in the menu and the other with 5 items. Both using the same CSS.

div.menu {
  display: table;
  color: white;
  text-align: center;
  width: 100%;
  font-size: 110%;
  background-color: #333;
}
div.menu a {
  display: table-cell;
  padding: 15px;
  text-decoration: none;
  color: white;
}
div.menu a:hover {
  background-color: #777;
}
<div class="menu">
  <a href="#">Item 1</a>
  <a href="#">Item 2</a>
  <a href="#">Item 3</a>
</div>


<br/>
<br/>

<div class="menu">
  <a href="#">Item 1</a>
  <a href="#">Item 2</a>
  <a href="#">Item 3</a>
  <a href="#">Item 4</a>
  <a href="#">Item 5</a>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.