css五种图片垂直居中的方法--亲测

html

<html>

<head>
  <title>水平垂直居中的所有方法title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="./style/index.css">
head>

<body>
  <fieldset>
    <legend>flex布局legend>
    <div class="flex-box">
      <img src="./imgs/timg.jpg" alt="卡通图案">
    div>
  fieldset>
  <fieldset>
    <legend>应用translatelegend>
    <div class="translate-box">
      <img src="./imgs/timg.jpg" alt="卡通图案">
    div>
  fieldset>
  <fieldset>
    <legend>纯absolute布局legend>
    <div class="absolute-box">
      <img src="./imgs/timg.jpg" alt="卡通图案">
    div>
  fieldset>
  <fieldset>
    <legend>table-celllegend>
    <div class="table-box">
      <div class="inner-table-box">
        <img src="./imgs/timg.jpg" alt="卡通图案">
      div>
    div>
  fieldset>
  <fieldset>
    <legend>calclegend>
    <div class="calc-box">
      <img src="./imgs/timg.jpg" alt="卡通图案">
    div>
  fieldset>
body>

html>

css

fieldset{
  float: left;
}
div{
  border: 1px solid #ccc;
  height: 300px;
  width: 300px;
}
img{
  width: 100px;
}
.flex-box{
  display: flex;
}
.flex-box img{
  margin: auto;
}

.translate-box{
  position: relative
}
.translate-box img{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}

.absolute-box{
  position: relative;
}
.absolute-box img{
  position: absolute;
  margin: auto;    
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

.table-box{
  display: table;
}
.inner-table-box{
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}

.calc-box{
  position: relative;
}
.calc-box img{
  position: absolute;
  top:calc(50% - 50px);
  left:calc(50% - 50px);
}

github 地址:https://caraxiong.github.io/css-center/src/index.html

转载于:https://www.cnblogs.com/cara-front-end/p/8488034.html

你可能感兴趣的:(css五种图片垂直居中的方法--亲测)