How to vertically align two or more (side by side) elements in a div?

百般思念 提交于 2019-11-27 18:10:37

问题


I am trying to vertically align two elements with different heights in a div:

<div class="footer-icons">
    <div id="footer-twitter">
         <img src="images/twitter.png" width="40" alt="">    
    </div>
    <div id="footer-fb">
         <div class="fb-like" data-href="http://facebook.com/user" data-send="false" data-layout="button_count" data-width="160" data-show-faces="false" data-font="arial"></div>
    </div>
</div>

The twitter div has a height of 40px, and the fb div has a height of 20px. What is currently happening is the fb div is vertically centered with the bottom edge of the twitter image. Here's the CSS:

.footer-icons {
    padding-top:40px;
    width:300px;
    margin:auto;
    text-align:center;
    vertical-align:middle;
}

#footer-twitter {
    display:inline-block;
}

#footer-fb {
    display:inline-block;
}

What am I doing wrong?


回答1:


Put the vertical align on the inner divs

#footer-twitter{
  display:inline-block;
  vertical-align:middle;
}

#footer-fb{
  display:inline-block;
  vertical-align:middle;
}



回答2:


Simple answer:

💪

Long answer:

display: flex is a pretty cool tool to have in your toolbelt. Here is some helpful documentation to get you started with it.

Specifically in your case these properties would be useful:

align-items:center - this will vertically align the centers of all child elements

justify-content:center - this will horizontally center child elements within the parent container (not sure you want this or not, but may be helpful as well)

.footer-icons {
    border: 1px solid #000;
    padding-top:40px;
    width:300px;
    margin: auto;
    
    display:flex;
    align-items:center;
    justify-content:center;
}
<div class="footer-icons">
    <div id="footer-twitter">
        Center me  
    </div>
    <div id="footer-fb">
         <img src="https://upload.wikimedia.org/wikipedia/commons/c/cd/Facebook_logo_%28square%29.png" width="40" alt="">   
    </div>
</div>



回答3:


Define a line-height equal or greater than the bigger icon:

.footer-icons {
    ...
    line-height: 32px;
}



回答4:


Just add display: flex; align-items: center; in .footer-icons CSS will resolve your issue. Thanks

.footer-icons {
    padding-top:40px;
    width:300px;
    margin:auto;
    text-align:center;
    vertical-align:middle;
    display: flex;
    align-items: center;
}


来源:https://stackoverflow.com/questions/12569980/how-to-vertically-align-two-or-more-side-by-side-elements-in-a-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!