Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - Position an element in percent from its own width

Tags:

html

css

I would like to position the center of an element (regardless of its height) over the bottom of its parent. I thought i'd go with absolute but nothing really makes sense. See picture below :

enter image description here

<div id="red">
    <div id="blue"></div>
</div>

How can I have this result ?

EDIT : Thanks to @Gaby aka G. Petrioli I found my solution :

#red{
  width: 300px;
  height: 200px;
  background: red;
  position:relative;
}
#blue{
  width: 100px;
  height: 50px;
  background: blue;
  right:3%;
  
  /* here is the magic solution*/
  position:absolute;
  bottom: 0;
  transform: translateY(50%);
}
<div id="red">
        <div id="blue"></div>
    </div>
like image 792
Marine Le Borgne Avatar asked Sep 10 '17 15:09

Marine Le Borgne


2 Answers

You should use absolute position to place it at the bottom, and then use transform translate to move it 50% upward since that work in regard to its own height.

So

.red{position:relative}
.blue{
   position:absolute;
   top:100%;
   right:50px;
   transform:translateY(-50%);
}
like image 54
Gabriele Petrioli Avatar answered Oct 05 '22 23:10

Gabriele Petrioli


You can use CSS Positioning, like:

.red {
  position: relative;
}

.blue {
  position: absolute;
  top: 100%; // Will be at exact bottom
  left: 50%;
  transform: translate(-50%, -50%); // Will pull 50% (of blue) upwards & 50% from the right as well
}

.red {
  background: red;
  width: 200px;
  height: 300px;
  position: relative;
}

.blue {
  background: blue;
  width: 100px;
  height: 200px;
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="red">
  <div class="blue"></div>
</div>

Hope this helps!

like image 45
Saurav Rastogi Avatar answered Oct 06 '22 00:10

Saurav Rastogi