如何使一行图像垂直和水平居中div?

时间:2019-06-15 22:54:58

标签: html css

我试图以任何屏幕尺寸在页面上居中放置一行图像。

.content img {
  width: 30%;
  height: auto;
}

.content {
  position: absolute;
  top: 50%;
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}
<body class="body_background">
  <div class="content">

    <a href="/index.html">
      <img src="http://lorempixel.com/400/200/"></img>
    </a>

    <a href="/index.html">
      <img src="http://lorempixel.com/400/200/"></img>
    </a>

    <a href="/index.html">
      <img src="http://lorempixel.com/400/200/"></img>
    </a>
  </div>

  <!-- video -->
  <div class="container">
    <video autoplay loop muted>
            <source src="background.mp4" type="video/mp4">
        </video>
  </div>

</body>

图像当前在Y方向上居中。除非我使用text-align:center,否则它们不在x的中心,但是边距不均匀。

2 个答案:

答案 0 :(得分:2)

尝试flexbox模型: 容器div应该具有:

display:flex;
align-items:center;
justify-content:center;
flex-direction:column;
padding-top:somevalue;

答案 1 :(得分:0)

这是一个解决方案,您可以尝试一下。谢谢:)

#container {
  display: flex;
  /* establish flex container */
  flex-direction: column;
  /* make main-axis vertical */
  justify-content: center;
  /* align items vertically, in this case */
  align-items: center;
  /* align items horizontally, in this case */
  height: auto;
  /* for demo purposes */
  border: 1px solid black;
  /* for demo purposes */
  background-color: #eee;
  /* for demo purposes */
}

.box {
  width: 100%;
  margin: 5px;
  text-align: center;
}

#bluebox {
  background: aqua;
}

#redbox {
  background: red;
}

#greenbox {
  background: green;
}
<div id="container">
  <!-- flex container -->

  <div class="box" id="bluebox">
    <!-- flex item -->
    <img src="http://highresolution.photography/images/tree-in-sunset-main.jpg" width="300px" alt="">
  </div>

  <div class="box" id="redbox">
    <!-- flex item -->
    <img src="https://images.unsplash.com/photo-1500382017468-9049fed747ef?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" width="300px" alt="">
  </div>

  <div class="box" id="greenbox">
    <!-- flex item -->
    <img src="https://images.unsplash.com/photo-1500622944204-b135684e99fd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" width="300px" alt="">
  </div>