在div中垂直居中图像

时间:2017-10-26 16:04:36

标签: css

基本上屏幕分为2部分,左侧为徽标,右侧为赞助商图像。

我想将两个图像垂直对齐在屏幕中心。现在图像在屏幕顶部对齐。我不明白怎么解决。你能给点暗示吗?

#logo {
    float:left;
    width: 50%;
    height:100%;
}
#imgLogo {
    height:100%;
}
#sponsor {
    float:left;
    width: 50%;
    height:100%;
    background:#ffffff;
    display: inline-block;
    vertical-align: middle;
}
#imgSponsor {
    max-height:90%;
    max-width:90%;
    display: inline-block;
    vertical-align: middle;
}
.app {
    position:absolute;
    left:0%;
    top:0%;
    height:100%;
    width:100%;
    text-align:center;
}
<div class="app">
    <div id="logo">
        <img id="imgLogo" src="logo.png">
    </div>

    <div id="sponsor">
        <a href="#">
            <img id="imgSponsor" src="http://www.foo.bar/wp-content/uploads/2017/10/foobar.jpg">
        </a>
    </div>
</div>

3 个答案:

答案 0 :(得分:0)

以下是使用flexbox

进行布局的方法

body {
  margin: 0;
}

.app {
  display: flex;
  align-items: center;
  height: 100vh;
}

.app div {
  flex: 1;
}

img {
  width: 100%;
  height: auto;
}
<div class="app">
  <div id="logo">
    <img id="imgLogo" src="https://unsplash.it/200x200">
  </div>

  <div id="sponsor">
    <a href="#">
      <img id="imgSponsor" src="https://unsplash.it/200x200">
    </a>
  </div>
</div>

答案 1 :(得分:0)

这就是CSS flex非常方便的地方:

body {
  margin: 0;
}

.app {
  display: flex;
  width: 100vw;
  height: 100vh;
  align-items: center;
  justify-content: space-around;
}

#sponsor, #logo {
  width: 50%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

#imgLogo {
  height: 100%;
}

#imgSponsor {
  max-height:90%;
  max-width:90%;
}

#sponsor a {
  display: flex;
  width: 100%;
  height: 100%;
  align-items: center;
  justify-content: center;
}
<div class="app">
    <div id="logo">
        <img id="imgLogo" src="https://placehold.it/200x200">
    </div>

    <div id="sponsor">
        <a href="#">
            <img id="imgSponsor" src="https://placehold.it/200x200">
        </a>
    </div>
</div>

答案 2 :(得分:0)

您可以在代码中使用这些2,这会使您的图像居中居中。

&#13;
&#13;
#logo {
    float:left;
    width: 50%;
    height:100%;
}
#imgLogo {
    height:100%;
}
#sponsor {
    float:left;
    width: 50%;
    height:100%;
    background:#ffffff;
    display: inline-block;
    vertical-align: middle;
    text-align: center;
}
#imgSponsor {
    max-height:90%;
    max-width:90%;
    display: inline-block;
    vertical-align: middle;
}
.app {
    position:absolute;
    left:0%;
    top:0%;
    height:100%;
    width:100%;
    text-align:center;
}
&#13;
<div class="app">
    <div id="logo">
        <img id="imgLogo" src="logo.png">
    </div>

    <div id="sponsor">
        <a href="#">
            <img id="imgSponsor" src="http://www.foo.bar/wp-content/uploads/2017/10/foobar.jpg">
        </a>
    </div>
</div>
&#13;
&#13;
&#13;

或者您可以使用:

background-position: center center: