I have a block (200x400). And inside this block there is another block (50x50). I want that when the window is resized, this child block is always in the center (height).

No matter how I do, with positioning relative: top 50%, margin-top does not help. The block is still shifting. Who will tell you how to solve this problem?

  • one
    Do you want the child block to be centered relative to the parent or window? - Ridzhi
  • regarding the parent - navi1893

2 answers 2

Two ways, if you know the width and height of the block, and if not:

Example

* { margin: 0; padding: 0; } section, div { position: relative; display: block; float: left; width: 200px; height: 200px; margin-right: 10px; border: 1px solid red; } article, p { width: 50px; height: 50px; background: blue; } /*1 cпособ */ /*если знаем высоту и ширину блока*/ article { position: absolute; top: 50%; left: 50%; margin: -25px 0px 0px -25px; } /*2 cпособ */ /*если НЕзнаем высоту и ширину блока*/ p { display: inline-block; vertical-align: middle; height: 30%; width: 30%; } div { text-align: center; } div:after { content: ''; display: inline-block; vertical-align: middle; height: 100%; width: 1px; } 
 <section> <article></article> </section> <div> <p></p> </div> 

  • About the middle, I did not know ... Thank you! - navi1893

for child

 position: absolute; width: 50px; height: 50px; top:calc(50% - 25px); 

and do not forget to set the parent position: relative