This is the 8th day of my participation in Gwen Challenge
Method a parent element setting :grid grid layout,align-content: center; justify-content: center; Center display
.section-one{
display: grid;
align-content: center;
justify-content: center;
}
.items-one{
background-color: powderblue;
}
Copy the code
Magin: Set top left right bottom to 0.
.section-two{
position: relative;
}
.items-two{
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background-color: yellow;
}
Copy the code
Method 3: Table-cell realizes the horizontal and vertical center of text content, and the margin attribute becomes invalid after setting
.section-three{
position: relative;
}
.items-three{
background-color: #6495ED;
/* Text center display */
display: table-cell;
vertical-align: middle;
text-align: center;
position: relative;
top: 100px;
left: 75px;
}
Copy the code
Margin :auto; margin:auto; Center display
.section-four{
display: table;
}
.items-foour{
display:table-cell;
vertical-align: middle;
background-color:darkcyan;
}
Copy the code
Method 5: parent element setting :grid grid layout, child element align-self: center; justify-self: center; Center display
.section-five{
display: grid;
}
.items-six{
align-self: center;
justify-self: center;
}
Copy the code
Margin :auto; margin:auto; Center display
.section-six{
display: flex;
}
.items-six{
background-color: crimson;
margin: auto;
}
Copy the code
Method 7: Absolute positioning method: determine the width and height of the current div, using the margin value of the current div width height half of the negative
.section-seven{
position: relative;
}
.items-seven{
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
background-color: coral;
}
Copy the code
Flex layout: Add a Flex style to the parent element, and set the width and height of the parent element to */
.section-eight{
display: flex;
justify-content: center; /* The left and right center alignment of the elastic layout */
align-items: center; /* Vertical center alignment of elastic layout */
}
.items-eight{
background-color: greenyellow;
}
Copy the code
Transform: translate(-50%,-50%); transform: translate(-50%,-50%); Add position: relative to parent of current div
.section-nine{
position: relative;
}
.items-nine{
position: absolute;
top: 50%;
left: 50%;
/* The translate() function is new to CSS3. In the case of not knowing its width and height, it can be used for horizontal and vertical center */
transform: translate(-50%, -50%);
background-color: red;
}
Copy the code