Position items relative to parent

Is it possible to place elements related to parents of parents?

<div id='div1'>
   <div id='div2'>
       <input type='button' class='btn'> button 2</button>
       <input type='button' class='btn'>button 3</button>
       <input type='button' class='btn'>button 1</button>
   </div>
</div>

It takes css to position the buttons relative to the first div in the center vertically, the css I tried

.btn{
     position: relative;
     top: 50%;
     transform: translateY(-50%)
  }

but this will center it relative to the second div. Perhaps this is different from the size of the parent div?

+4
source share
2 answers

checkout the fiddle https://jsfiddle.net/3531chbz/1/

The trick is that you should not give an attribute position:for the second div, i.e. #div2, therefore, in this case, the child in the second div will take a position with his great parent,

you must also change the input position to position:absolute

HTML

<div id='div1'>
   <div id='div2'>
       <button class='btn'> button 2</button>
       <button class='btn'>button 3</button>
       <button class='btn'>button 1</button>
   </div>
</div>

CSS

#div1 {
    position:relative;
    background-color:green;
    height:400px
}
#div2 {
    background-color:blue;
    height:200px;
    text-align:center;
}
.btn {
    position:absolute;
    top: 50%;
    transform: translateY(-50%)
}
0
source

div2, .

: <input type='button' class='btn'> button 2</button> HTML

#div1 {
  height: 250px;
  position: relative;
  background: lightgreen;
}
#div2 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: red;
}
<div id='div1'>
  <div id='div2'>
    <button class="btn">button 2</button>
    <button class="btn">button 3</button>
    <button class="btn">button 1</button>
  </div>
</div>
Hide result
0

Source: https://habr.com/ru/post/1589178/


All Articles