简体   繁体   中英

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. inside that container I want to add another square div 72x72px which will be centered both horizontally and vertically. 例

css solution is preferred

thanks for the help

current 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/

html

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

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..

 .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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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