html - 保持图像在 h1 旁边,无论屏幕大小如何,两者都居中

标签 html css

寻找一种解决方案,使用户的个人资料图片保持在 h1 旁边,并使它们居中,两边的边距相等,而不管屏幕尺寸如何。 h1 通过文本对齐居中,但我不知道如何让 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-->

最佳答案

使 h1 和 img display: inline-block 并移除 float 。它们都将以 div 上现有的 text-align: center 为中心。

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

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

工作示例

在这个例子中,我已经删除了主体的默认边距以及不需要的填充底部。

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

关于html - 保持图像在 h1 旁边,无论屏幕大小如何,两者都居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27052932/

相关文章:

css - 如何使用多个图像背景和 :hover pseudo 在 CSS 中制作翻转图像

html - 列中间的垂直对齐按钮 - bootstrap

html - 在父容器 Bootstrap 中填充图像

html - CSS 在所有浏览器中都不起作用

html - 在 TreeView 中查看 HTML 源代码?

html - 这个 HTML 有效吗?

javascript - JQuery Mobile - JavaScript 何时加载到 DOM 中?

javascript - jquery 两个元素

javascript - Window.click 事件不会在 IOS safari 上触发 - 仅限 JavaScript

CSS3 过渡 - Javascript 库