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 will set the parent's width and center it <div class= "center" >//subcomponents we're going to implement it vertically centering not setting his width height wide All the images introduced by the following IMG are open </div> </div>
Here is the style code
. wrap{set a centered outer frame width:500px;height:400px;border:1px solid black;margin:0 auto;text-align:center;//Horizontal Center}.wrap:b efore{//set a pseudo-class with a width of 0 why this pseudo-class is set up when this pseudo class plays the role of a crosshair display:inline-block;content: "; height:100%;width:0; vertical-align:middle;//Vertical Center}.center{//This time in our Centerdiv set 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 outer frame width:500px;height:400px;border:1px solid black;margin:0 Auto;} . center{//Our Center div is also written in inline-block style position:relative; Relative positioning allows the upper-left corner of the center div to be in the center of wrap by relative positioning the setting of the top value. But this time we're not completely vertically centered because our center Div itself has an adaptive width. Transform//through Translatex ( -50%) Translatey (-50%) Let center itself offset 50% on the y axis of the x axis to True center (the pivot point default in the 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>