首页 > 解决方案 > 如何使用 Flexbox 制作不对称的东西

问题描述

所以我用 HTML 和 CSS 构建了一个小文本小部件。它看起来不错并且符合预期,但是由于我没有使用 FlexBox 进行此操作,因此在某些站点上显示错误。通过使用硬编码设置位置,“Place here”图标和“To the Job”被放置在那里。根据文档的宽度,硬编码使小部件看起来变小或变长。所以我希望他们灵活。但我不知道如何进行灵活安排,看起来像这样。每个文本和图标都是不同的元素。我尝试过使用 flex,但是职位和职位描述之间的空白差距太大。感谢您的帮助,并对愚蠢的问题感到抱歉。

在此处输入图像描述

标签: htmlcssflexbox

解决方案


这里有一个简单的例子:

首先考虑如何构建 HTML。我在这里看到的是 1 个大盒子,里面有 3 个孩子。Job Title Here并且Description of the Job here是第一个子元素的子子元素。

如果你放在display: flex大盒子上,孩子们会在旁边对齐以水平吃其他人。

现在在这一点上看起来很丑,他们粘在一起。让他们远离吃其他套装justify-content: space-between。它在孩子们之间增加了尽可能多的空间,因为他们可以进入盒子。

现在我们遇到了问题,它们没有垂直对齐。在这里你需要设置align-items: center这将使孩子在flexbox内居中

* {
   margin: 0; 
   padding: 0;
   box-sizing: border-box;
   font-family: "Arial", sans-serif;
}

.box {
  border: 1px solid #dadada;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding:20px;
  box-shadow: 0 0 5px lightgrey;
  margin: 10px;
}


h2 {
   color: darkorange;
}

#tojob {
   cursor: pointer;
   position: relative;
}
#tojob::before {
   content: "";
   position: absolute;
   left: 0;
   width: 0;
   height: 2px;
   bottom: 0;
   background: darkorange;
   transition: width 200ms;
}

#tojob:hover::before {
     width: 100%;
}
<div class="box">
   <div>
      <h2>Job title here</h2>
      <p>description here</p>
   </div>
   <p style="margin-left: auto">Place here</p>
   <p id="tojob" style="margin-left: 25%">to the job</p>
</div>


推荐阅读