Please tell me how to position the block exactly in the middle of the screen, horizontally through margin: 0 auto, and how to do it vertically?
3 answers
There are lots of options.
1. With line-height
2. Absolute positioning
3. Using padding
4. Using tables
5. Using flexbox
6. Using transform
7. With a negative margin-top
8. Using the pseudo-element: before
Choose whatever you like best.
Alignment with: before:
This method works only if the indoor unit does not have absolute positioning.
.wrapper { text-align: center; // другие стили для блока-родителя display: block; height: 200px; } .wrapper:before { content: ""; display: inline-block; height: 100%; vertical-align: middle; } .inner { display: inline-block; vertical-align: middle; // другие стили для внутреннего блока } <div class="wrapper"> <div class="inner">Lorem ipsum</div> </div> - I would be very grateful if you describe how to make the current through: before, and pading. But thanks to that too! - monvl
- Added with: before. Indented can be used if you know the heights of both blocks .wrapper {height: 100px; text-align: center;} .inner {height: 50px; margin: 25px 0;} - Alex
- @Alex is better to add
heightfor.wrapperso that in the example when executing the code, the alignment in the middle of the block is visible, now in the example it is not visually visible that the block is aligned in the middle of the.wrapper. - Alex
|
You can use the flex property, or you can:
.par { width: 200px; height: 200px; border: 1px solid #000; display: table-cell; vertical-align: middle; text-align: center; } .ch { width: 5px; height: 5px; background-color: red; display: inline-block; } <div class="par"><div class="ch"></div></div> |
It is possible so through flexbox :
* { margin: 0; padding: 0; } body, html { height: 100%; } #cont { display: flex; align-items: center; justify-content: center; height: 100%; } #cont div { width: 50px; height: 50px; background-color: #f1f1f1; } <div id='cont'> <div></div> </div> |