简体   繁体   English

在容器div中将2 div分别居中

[英]Centering 2 divs seperatly inside a container div

I'm looking for a solution for this problem: I have a container div which gets its height / width from a div/img inside it with dynamic height. 我正在寻找此问题的解决方案:我有一个容器div,它可以从其中具有动态高度的div / img中获取其高度/宽度。 inside that container I want to add another square div 72x72px which will be centered both horizontally and vertically. 在该容器内,我想添加另一个正方形div 72x72px,它将水平和垂直居中。 例

css solution is preferred 最好使用CSS解决方案

thanks for the help 谢谢您的帮助

current html: 当前HTML:

<div class="post">
    <div class="post-like"></div>
    <img src="dsada"/>
</div>

current less: 当前减:

.post:before{
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
  background: #808080; width: 5px;
}

    .post{
  background:  @white;
  direction: rtl;
  overflow: hidden;
  width: 42%;
  margin-left: 2%;
  margin-right: 2%;
  margin-top: 4%;
  position: relative;
  text-align: center;
  white-space: nowrap;
img{
display: inline-block;
vertical-align: middle;
width: 100%;
}
 .post-like
    display: inline-block;
    vertical-align: middle;
    opacity: 1;
    cursor: pointer;
    height: 72px;
    width: 72px;
    border-radius: 50%;
    background: rgba(0,0,0,0.7);

    }

There is a pretty old trick which work for this case 有一个很老的技巧可以在这种情况下工作

http://jsfiddle.net/9x1zLhz8/ http://jsfiddle.net/9x1zLhz8/

html html

<div class="container">
    <img src="http://placehold.it/200x500" alt="" />
    <div class="inner"></div>
</div>

css 的CSS

.container {
    float: left;
    margin: 20px;
    position: relative;
}
.inner {
    background: #fff;
    border: 2px solid #333;
    width: 72px;
    height: 72px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin: -36px 0 0 -36px;
}

You can use the display:table to shrink div on content(image) and then the oldish relatif/absolute way of centering things to stick your box over the image.. 您可以使用display:table缩小内容(图像)上的div,然后使用老式的相对/绝对居中方法将框固定在图像上。

 .ib { display:table; margin:auto; position:relative; } .top { z-index:1; position:absolute; top:50%; left:50%; background:rgba(255,255,255,0.75); } .h72.w72.center { height:72px; width:72px; margin:-36px; } picture,legend { box-shadow:0 0 5px, inset 0 0 2px; text-align:center; } picture img { display:block; } /* extra if understood by browser*/ .flex { display:flex; flex-direction:column; justify-content:center; } 
 <picture class="ib"> <img src="http://lorempixel.com/200/400"/> <legend class="h72 w72 center top flex"> center top layer </legend> </picture> 

Codepen to play with 与Codepen一起玩

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM