【问题标题】:Keep image beside h1, both centered regardless of screen-size将图像保留在 h1 旁边,无论屏幕大小如何,都居中
【发布时间】:2015-01-19 02:26:01
【问题描述】:

寻找一种解决方案,将用户的个人资料图片保留在 h1 旁边,并使它们都居中,两边的边距相等,无论屏幕大小如何。 h1 通过 text-align 居中,但我不知道如何将 img 保持在 h1 旁边。目前, img 向左浮动,当我注释掉 float: left 时,img 居中,h1 消失。下面是同时保存 img 和 h1 的 div 的代码,然后是分别保存 img 和 h1 的代码。

.biohead {
    width: 100%;
    position: fixed;
    text-align: center;
    display: block;
    padding-bottom: 1%;
    color: dimgray;
    font-size: 2.5em;
    box-shadow: 0 0 15px rgba(0, 0, 0, .2);
}
.biohead img {
  height: 50px;
  border-radius: 39px;
  width: 50px;
  margin-top: 5px;
  float: left;
  margin-left: 5px;
  margin-right: 5px;
  margin-bottom: 5px;
  /*margin-left: 15%;*/
  /*margin-right: 11px;*/
}
.biohead h1 {
/*    float: left;
*/    margin: 0 auto;
    margin-top: 10px; 
}

和 html :

  <div class="biohead">
     <img src="images/fisherman.png" alt="Raul">
     <h1>Raul Pescadero</h1> 
  </div> <!--biohead-->

【问题讨论】:

    标签: html css


    【解决方案1】:

    制作 h1 和 img display: inline-block 并删除浮动。它们都将以 div 上现有的text-align: center 为中心。

    另外,将它们都设置为vertical-align: middle,因为默认的baseline 值可能会导致其他元素出现意外行为。

    目前,包装 div 应该有一个合适的min-width,这样它就不会变得太小而导致断线。

    工作示例

    在此示例中,我已从正文中删除了默认边距以及不需要的 padding-bottom。

    body {
    margin: 0;  
    }
    
    .biohead {
      width: 100%;
      position: fixed;
      text-align: center;
      display: block;
      color: dimgray;
      font-size: 2.5em;
      box-shadow: 0 0 15px rgba(0, 0, 0, .2);
      min-width: 600px;
    }
    .biohead img {
      height: 50px;
      border-radius: 39px;
      width: 50px;
      display: inline-block;
      vertical-align: middle;
      margin: 0 5px;
    }
    .biohead h1 {
      display: inline-block;
      vertical-align: middle;
    }
    <div class="biohead">
      <img src="http://www.placehold.it/50" alt="Raul">
      <h1>Raul Pescadero</h1> 
    </div>
    <!--biohead-->

    【讨论】:

    • 这很有效,并立即让我想起了这个网站的美丽。谢谢@misterManSam。 虚拟弓
    猜你喜欢
    • 2011-09-22
    • 2021-04-20
    • 2023-02-15
    • 1970-01-01
    • 2017-11-12
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    相关资源
    最近更新 更多