Two ways to center up and down html and js Images
Recently I have encountered the problem of center the picture up and down, and set it directly in the left-right corner.
- Margin: 0 auto; it's okay. It won't work if you look up and down in the center. There are two methods that are successful after multiple tests:
One js implementation and one css implementation:
1. Align the image in js:
1. First, you must know the image height range: div_height. 2. because the image height is obtained after the image is loaded, the js function call cannot use $ (document ). ready (), $ (window) is required ). load (function {......}), The reason is that the former is called after the page framework is loaded, and the latter is called only after all the page elements, including the image, are loaded. 3. Obtain the Image Height img_height. 4. Set the image's margin-top = (div_height-img_height)/2.
Example: The height range is 220 pxhtml:
Js: $ (window). load (function (){
Var img_height = $ (this). height ();
Var margin_top = (220-img_height)/2;
((This).css ({"margin-top": margin_top + "px "});
});
2. Set the Image Height center in html + css (assuming that the div height containing the image is div_height = 600px, and the image height is smaller than 600px). 1. Set the parent div of the image (this document assumes that it is 600px ).
- Line-height: 600px; // The picture is centered up and down at the height of 600px, which can be modified as needed
- Display: table-cell;
- Vertical-align: middle;
2. Note that the height of the parent div must be equal to the height displayed in the image. Example:
Html:
Css:
. Carousel {
Height: 600px;
Line-height: 600px;
Display: table-cell;
Vertical-align: middle;
}
-
-
- Height: 600px;
- Line-height: 600px;
- Display: table-cell;
- Vertical-align: middle;