Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Performance wise, better to use calc or position absolute

I have a container div with fixed height. Inside two divs, the top height: 50px and the other one must fill the empty space but allowing internal scroll.

Now I have two options:

#up{
    height: 50px;
}

#down{
    position: absolute;
    top: 50px;
    bottom: 0;
}

or:

#up{
    height: 50px;
}

#down{
    height: calc(100% - 50px);
}

If I have many of these cases inside my window, which one is the best to use performance wise?

This Fiddle

ps. I don't care about old browser support.

like image 903
kiwi1342 Avatar asked Apr 30 '15 10:04

kiwi1342


People also ask

Is calc in CSS slow?

Yes it would be slower. Just avoid css calc where ever you can.

When should you use absolute positioning CSS?

When position absolute is used on an element, it is positioned absolutely with reference to the closest parent that has a position relative value. If there are no parent elements that has a relative position, then the absolutely positioned element will take its reference from the browser window.

Why is it better to use translate () rather than an Position absolute top right bottom left?

TLDR: Using transform: translate(x,y); greatly decreases paint times on elements with CSS transitions. However, position: absolute; top/left will be faster if used on elements without transitions. Why Moving Elements with translate is better than position absolute, top/left (Paul Irish):

Should I use position absolute or relative?

If you specify position:relative, then you can use top or bottom, and left or right to move the element relative to where it would normally occur in the document. Position Absolute: When you specify position:absolute, the element is removed from the document and placed exactly where you tell it to go.


2 Answers

I would always work with calc option. Both could look the same but they are not.

When you use position:absolute You are taking the container #down out of the html flow.

This means that if anytime you are going to add more stuff to your project, You will have many problems positioning them.

As an example, if you want to add another container below #down (a footer maybe), in your first option it will be placed overlapping #down container right below your header. In the second option it will be placed where you want it.

like image 54
Alvaro Menéndez Avatar answered Oct 22 '22 20:10

Alvaro Menéndez


One way to fill the space would be to use flexbox.

.container {
  display: flex;
  flex-direction: column;
  height: 200px;
}

#up {
  background: yellow;
  flex: 0 0 50px;
}

#down {
  background: orange;
  flex: 1 1 auto;
}
<div class="container">
  <div id="up">
    up
  </div>
  <div id="down">
    down
  </div>
</div>
like image 28
Veiko Jääger Avatar answered Oct 22 '22 21:10

Veiko Jääger