How to center a block. CSS Examples open

How to center a block. CSS Examples

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

Very often the task is to align the block to the center of the page / screen, and even so that without a java script, without setting hard sizes or negative indents, so that the scrollbars work on the parent if the block exceeds its size. There are quite a lot of monotonous examples on the net of how to align a block to the center of the screen. As a rule, most of them are based on the same principles.

More information – https://www.w3.org/Style/Examples/007/center.ru.tmpl

Method 1 – margin auto

Method 1 - margin auto

.div {
    display: block;
    width: 300px;
    margin-left: auto;
    margin-right: auto 
}

To align also vertically add to your CSS vertical-align: middle

.div {
    display: block;
    width: 300px;
    margin-left: auto;
    margin-right: auto;
    vertical-align: middle 
}

If you want to align vertically position: absolute block

.container {
   position: relative 
}              
.div {
   margin: 0;
   position: absolute;               
   top: 50%;                         
   transform: translate(0, -50%)
 }   

Vertically position absolute block

CSS3 Vertical and horizontal alignment

.container {
    position: relative 
}
.div {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%)
 }

CSS3 Vertical and horizontal alignment

Modern flex Vertical and horizontal alignment

.container {
  display: flex;
  align-items: center;
  justify-content: center 
}
.div {
  margin: 0 
}

Modern flex Vertical and horizontal alignment

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation