Why is the block with class c2 not aligned to the center of the block with class c1 ?

 .c1 { width: 200px; height: 200px; background: red; } .c2 { width: 50px; height: 50px; background: green; vertical-align: middle; } 
 <div class="c1"> <div class="c2"> </div> </div> 

    3 answers 3

    It is possible so (to make c2 line element):

     .c1 { width: 200px; height: 200px; line-height: 200px; background: red; text-align: center; } .c2 { width: 50px; height: 50px; background: green; display: inline-block; vertical-align: middle; } 

    More ways here.

      First of all, vertical-align applies only to string elements or table cells: description vertical-align

      Applies : To string elements or table cells

      However, if you specify a lowercase version of the display to the internal block, applying vertical-align will not do anything to it, since the lowercase blocks are aligned vertically with respect to the neighboring blocks, and in your case there is only one block.

      It is also not very reasonable to make an external block a table only for alignment, for semantically it will be wrong.

      You can use the line-height , the value of which will be equal to the height of the external block. But if the height is unknown, then this method is also not universal.

      You can choose the most suitable vertical alignment method by the link: All vertical alignment methods in CSS

        vertical-align: middle; it works only for string elements and table cells. If you want to do for the blocks, you can do this:

         .c1 { width: 200px; height: 200px; background: red; display: table-cell; vertical-align: middle; /* выравнивание по высоте */ text-align: center; /* выравнивание по ширине */ } .c2 { width: 50px; height: 50px; background: green; display: inline-block; } 
         <div class="c1"> <div class="c2"> </div> </div>