首页 > 解决方案 > css中的中心对象

问题描述

我有这个 HTML 代码:

<div class='container'>
      <div class="post-container">
        <div class="post-thumb"><img src="../images/logo.png" /></div>
      </div>
      //A few other thigs
    </div>  

后容器高于其他东西。
现在我想将 post-thumb div 放在 post-container 中,并将图像放在 post-thumb 中。
但是怎么做呢?

这是CSS:

.post-container {
  overflow: auto;
  text-align:center;
}

.post-thumb {
  width:230px;
  height:50px;
  overflow:hidden;
  text-align:center;
  margin-left: auto;
  margin-right: auto;
  margin-top: auto;
  margin-bottom: auto;
}

.post-thumb img {
  width:100%;
  margin-left: auto;
  margin-right: auto;
  margin-top: auto;
  margin-bottom: auto;
}

.container {
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
  box-shadow: 1px 1px 5px #ddd;
  width: 250px;
  height: 100%;
  background-color: #2e3233;
}

标签: htmlcssimage

解决方案


使用弹性盒来居中:

.post-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.post-thumb {
  display: flex;
  justify-content: center;
  align-items: center;
}

.post-thumb img {
  max-width:100%;
}

这是一个小提琴https://jsfiddle.net/hwuLrn43/1/


推荐阅读