Fix Div with JavaScript

0

Good evening, I know that this doubt has been answered here several times, but none of it worked for me and I will explain why.

In all the solutions presented it is necessary to change the parameter position: relative; to position: fixed; , however this configuration has the inconvenience of having to do the manual centralization of Div, specifying its values in px or other parameter, the% of%, which should be width , because if you get out of self, the div of the menu bar does not scale itself according to the resizing of the browser window with the mouse, or the format of the pc of the user.

So I would like a purely javascript solution for this case, without CSS. Detail, I just want to fix, with no additional effect like animations, etc ... Thanks in advance.

    
asked by anonymous 17.09.2016 / 04:04

3 answers

0

The only way to "fix" with javascript is by listening to the scroll of the page and updating the position of the element in real time, but this will always generate a strange blink on the element, to really get fixed only with% / p>

$(window).scroll(function() {
  $('.fixa').css({"top": $(window).scrollTop() });
});
.conteudo {
  background-color: LightBlue;
  height: 2000px;
 }
.fixa {
  position: relative;
  background-color: ivory;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="conteudo">
  <div class="fixa">
    fixa!  
  </div>
  conteudo...
</div>
    
18.09.2016 / 01:52
-1

Does your div have width fixed? If so, you can centralize with CSS:

div.centralizada {
    position: fixed;
    width: 300px;
    left: 50%;
    margin-left: -150px;
}

You have to use left with 50% and "pull" the div half of its size: in the above example the div has width 300 then margin-left is 150 , which is half and 300. If the div has width 600 then margin-left would be 300. I think you could understand ...

    
17.09.2016 / 19:04
-1

You can create a div with the height and width you want:

Ex:

.conteudo{
 height: 100px;
 width: 100px;
}

Then just create another div with the following code:

.centred{
 display: flex; //Exibe um elemento como um recipiente flexível em nível de bloco . Novo em CSS3.
 flex-direction: row; //Valor padrão. Os itens flexíveis são exibidas horizontalmente , como uma linha.
 flex-wrap: wrap; //Valor padrão. Especifica que os itens flexíveis não será moldado.
 align-content: center; //As linhas são embalados na direcção do centro do recipiente flexível.
 align-items: center; //Os produtos são posicionadas no centro do recipiente.
}

Example usage:

.conteudo{
 height: 100px;
 width: 100px;
}

.centred{
 display: flex;
 flex-direction: row;
 flex-wrap: wrap;
 align-content: center;
 align-items: center;
}
<div class="conteudo">
  <div class="centred">
    Eu estou Testando...
  </div>  
</div>
    
17.09.2016 / 20:46