html - 如何在剩余空间中 float 图像并居中标题?

标签 html css sass alignment flexbox

我想要这个结构,一个有flex:display的容器,一个 float 在右侧的图像,然后是h1和h2,我想把这些垂直和水平中心放在div的剩余空间上。

这是我当前的结果。

enter image description here

样机。

+-----------------------+
|                       |
|XXXX                   |
|XXXX     HELLFISH      |
|XXXX    born to die    |
|XXXX                   |
|                       |
+-----------------------+

这是 html 代码。

div.container
  img(src='http://vignette3.wikia.nocookie.net/simpsons/images/a/a1/Flying_Hellfish_Logo.png/revision/latest?cb=20150327234211')
  h1 HELLFISH
  h2 Born to die

SCSS。

.container{
  display: flex;
  width: 50%;
  border: 1px solid red;
  justify-content: space-between;
  img{
    max-width: 300px;
    max-height: 300px;
    float: left;
  }
  h1{
    align-self: center;
    margin: auto;
    position: relative;
  }
  h2{
    align-self: center;
    margin: auto;
    vertical-align:middle;
    position: relative;
  }  
 }

代码笔。 http://codepen.io/TabaresSotelo/pen/pRyxPz

致以诚挚的问候

最佳答案

  • h1h2 包装在一个容器中(该容器成为图像的同级 Flex 元素)。
  • 使用 order 属性将图像向右移动。
  • 您不需要使用 float 属性或 justify-content: space- Between

.container {
  display: flex;
  width: 50%;
  border: 1px solid red;
}
.nested-container {
  flex: 1; /* to consume all remaining space */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.container img {
  max-width: 300px;
  max-height: 300px;
  order: 1;
}
h1, h2 {
  margin: 0;
}
<div class="container">
  <img src="http://vignette3.wikia.nocookie.net/simpsons/images/a/a1/Flying_Hellfish_Logo.png/revision/latest?cb=20150327234211" />
  <div class="nested-container">
    <h1>HELLFISH</h1>
    <h2>Born to die</h2>
  </div>
</div>

revised codepen (编译后的代码)

关于html - 如何在剩余空间中 float 图像并居中标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41618339/

相关文章:

html - 不显示Base64/SVG HTML图像

html - div 边框未包裹内容 css/html

html - 如何将我所有的 li 对齐在一条线上?

css - 包含 bootstrap.css.map 的正确方法?

css - 在不设置尺寸的情况下在 CSS 中裁剪图像

python - django-pipeline 不编译 sass 文件

javascript - 如何使用一个提交按钮在一个页面中提交 2 个表单

javascript - 如何防止指针在 HTML 中通过?

javascript - 如何为主要浏览器(以及 Chrome)转换(旋转)句子中的单个字母

css - 是否有 CSS 父级选择器?