简体   繁体   中英

HTML: Position element by the center of sibling

Sorry for a dump question. I have never work with HTML. I have following UI:

在此处输入图片说明

I would like to be Success centralized by the middle of sendMessage element.

<div style="position: relative; overflow: hidden;">
      <div style="position: relative; width: 40%; float: left; vertical-align:middle">
            <button class="btn btn-default">sendMessage</button>
      </div>
      <div style="position: relative; width: 40%; float: right; vertical-align:middle">
            <span class="label label-success" style="font-size: small;">Success</span>
      </div>
</div>

What am I doing wrong?

Try display: inline-block with vertical-align: middle like that:

 .send-button { display: inline-block; border: solid 1px black; background: #ccc; margin: 8px; padding: 8px; vertical-align: middle; } .success-info { display: inline-block; background: #9b8; color: white; vertical-align: middle; padding: 2px; font-weight: bold; } 
 <div class="parent"> <button class="send-button">Send Message</button> <div class="success-info">Success!</div> </div> 

Currently, they're two different divs, in a larger div. Both divs are being aligned according the larger div.

If you want to put those divs 'over' eachother, you'd have to use position:relative with an addition like: left 100px , in order to move the top div over the lower div (you may have to use a Z-index as well, in order to get the correct div on top).

Alternatively, it might work to place the 'success' div inside the 'button div'. If you then display the button as display:flex , and align the 'success div' to the center, it should work as well.

Its easier to use inline-block s instead of floating the divs. Try something like this:

 .box { display: inline-block; vertical-align: middle; border: 1px solid red; height: 50px; text-align: center; } .box:before{ display: inline-block; vertical-align: middle; content: ''; height: 100%; } .left { float: left; } .right { float: right; } 
 <div> <div class="box"> <button id="resetCache" class="btn btn-default">sendMessage</button> </div> <div class="box"> <span id="resetCacheResponse" class="label label-success" style="font-size: small;">message</span> </div> </div> 

You can achieve with only add

display: inline-block;

in same style code which you use

vertical-align: middle;

Because without setting display your code not work properly.

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