DIV element does not position next to "sidenav"

Asked

Viewed 48 times

-1

I’m creating a page that will have a fixed sidebar and a <div> with the main content of the page. Below is an example code:

.sidenav {
  height: 100%;
  width: 160px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  padding-top: 20px;
}

.sidenav a {
  padding: 6px 8px 6px 16px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
}
<div class="sidenav">
  <a href="#about">About</a>
  <a href="#services">Services</a>
  <a href="#clients">Clients</a>
  <a href="#contact">Contact</a>
</div>

<div class="main">
  <p>Aqui estará o conteúdo principal da minha página.</p>
</div>

The problem is, as you can see, the <div> is not positioned next to the sidenav.

For that, I would need to insert a margin-leftwith the exact width of the sidebar on <div>, but that’s not what I want. I want the <div> is automatically positioned next to the sidenav, so that it is not necessary to change its CSS code if there is a change in the size of the sidebar.

2 answers

0

Complementing what @Gelson.Gilmar said you can use a variable for the size as below

:root {
 --size-sidenav: 300px;
}

And so changing

.sidenav {
  height: 100%;
  width: var(--size-sidenav);
  background-color: #111;
  padding-top: 20px;
}

And the size of the main

.main {
  /* Coloquei o background red para facilitar a visualização. */
  background-color: red;

  /* O width vem do calculo de 100 da largura da tela subtraindo o tamanho do menu */
  width: calc(100vw - var(--size-sidenav));
}

That way when you change the width of the sidenav will already automatically adjust the main size.

-1

Follows a solution using flex-box.

* {
  /*O box-sizing como border-box para todos os itens, isso faz com que o padding e o marging não influenciem no width e no heigth*/
  box-sizing: border-box;
}

/* Fex para alinhar os itens na horizontal*/
.engloba {
  display: flex;
  flex-direction: row;
}

.sidenav {
  height: 100%;
  width: 160px;
  background-color: #111;
  padding-top: 20px;
}

.sidenav a {
  padding: 6px 8px 6px 16px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
}

.main {
  /* Coloquei o background red para facilitar a visualização. */
  background-color: red;

  /* O width vem do calculo de 100 da largura da tela subtraindo o tamanho do menu */
  width: calc(100vw - 160px);
}
<!-- Adicionei uma div englobando para definir o display flex -->
<div class="engloba">
  <div class="sidenav">
<a href="#about">About</a>
<a href="#services">Services</a>
<a href="#clients">Clients</a>
<a href="#contact">Contact</a>
  </div>

  <div class="main">
<p>Aqui estará o conteúdo principal da minha página.</p>
  </div>

</div>

Browser other questions tagged

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