When we write CSS style, we often encounter a problem that is a wide and high unknown element to let him vertically center how to achieve this? Here are two ways I used to do this.
On the Code
The following is the structure code
<div class= "Wrap" >//here is the parent component we set the parent's width and center it
<div class= "Center" >//subcomponents we're going to implement it vertically centered without setting his width and width height are all created by the following IMG introduction to the picture
</div>
</div>
Here is the style code
. wrap{set a centered frame
width:500px;
height:400px;
BORDER:1PX solid black;
margin:0 Auto;
text-align:center;//Horizontal Center
}
. wrap:before{//set a pseudo-class with a width of 0 why this pseudo class acts as a crosshair when the pseudo-class is set up
Display:inline-block;
Content: ";
height:100%;
width:0;
vertical-align:middle;//Vertical Center
}
. center{//this time in the Centerdiv setting of our vertical-align:middle can be vertically centered
Vertical-align:middle;
Display:inline-block;
}
img{
Vertical-align:top;
}
Two CSS3 Transform solution
. wrap{//a fixed-width-height-centered frame
width:500px;
height:400px;
BORDER:1PX solid black;
margin:0 Auto;
}
. center{//our Center div is still written in inline-block style.
position:relative;
Relative positioning allows the top left corner of the center div to be the center of wrap by relative positioning the setting of the leftmost top value
But at this point, we're not completely vertically centered because our center Div itself has an adaptive wide height, and it's going to be transform.
by Translatex ( -50%) Translatey (-50%) Let center itself shift 50% on the x axis to True Center (pivot point Default in upper left corner)
Note Transform Each browser has a different prefix and is incompatible IE8 the following
top:50%;
left:50%;
Display:inline-block;
-webkit-transform:translatex ( -50%) Translatey (-50%);
}
img{
Vertical-align:top;
}
<! DOCTYPE html>
CSS wide-height adaptive div element how to center vertically