Last Updated: February 25, 2016
·
5.748K
· elad2412

Dynamic element size via CSS position manipulation

A small trick that give a volume to element without using width & height or JS.

This is very easy tip, but a lot of people doesn't know it.

Let's say that you want to make a modal box that covers all screen except 100px each side, How would you solve this issue?

HTML

<div class="popup">some content</div>

First of all we need to add a property position:fixed To our div.
After that we want to position the modal box 100px from each side of the viewport, why shouldn't we give it all 4 position property parameter (top, right, bottom, left)?!

The solution is in the question, you can give all 4 parameters of the position fixed/absolute, top:100px , right:100px, bottom:100px; and left:100px;.
by doing that you are making the dynamic element size accordingly 100px from each side.

CSS

.popup{  
      position:fixed;
      z-index:5;
      left:100px;
      right:100px;
      top:100px; 
      bottom:100px;

      /*some styles*/
      background-color:#ccc;
      border-radius:10px;
      border:solid 3px #000;
      padding:20px; 
}

The resulting div is an auto size modal box without one line of JS!

Live Example

Now, Let's say you want to add mask underneath the modal box, exactly the same idea!
Here is the solution:

HTML

<div class="mask"></div>

CSS

.mask{
  position:fixed;
  z-index:2;
  left:0;
  right:0;
  top:0; 
  bottom:0;  
  background-color:rgba(0,0,0,0.8);  
}

Full Live Example

Note:
1. Cross Browser (Internet Explorer 8 And Above).

Enjoy!

If you like this tip, I will be happy to get your LIKE. You are welcome to follow me and endorse my skills.
Elad Shechter