如何在不同容器中对齐元素?

时间:2019-05-25 15:41:13

标签: html css flexbox

如何将标题与“右对齐”容器的左边缘对齐?这是我要实现的目标的草图:

mockup

我正在使用flexboxflex: 1创建50/50布局。我现在正尝试在正确的位置放置标题。我首先想到的是将其放入aligned-right子容器中,但是我不希望它扩展到aligned-left区域。

使用flexbox将子容器对准中心线是错误的方法吗?

这是一个缺少标题的小提琴: https://jsfiddle.net/cwasdbo4/17/

2 个答案:

答案 0 :(得分:0)

您可以将.title容器放入.aligned-right容器并添加(根据您的小提琴示例):

    .title {
      margin-top:-20px;
      position:relative;
      width:200%; //or white-space:nowrap;
    }
    .parent-container {
      margin-top:40px;
    }

但是对于两行或更多行(或者如果您动态添加内容)的长标题不起作用,并且相对布局绝对无济于事。

答案 1 :(得分:0)

尝试使用CSS flex这个简单示例

var off=$('#box-left').position().left-9;

$('.header > span').css('left',off+'px');
.main{
  width:100%;
  border:1px solid #000;     
}

.main .header{
   text-align:center;
}

.main .header span{
  display:flex;
  position: relative;
}

.main .container{
  width:100%;  
  display:flex;  
}

.main .container .box-section{
  width:50%; 
  height:130px;
   display:flex;
   background:#eff0f1;
  border:1px solid #000;
}

.main .container .box-section.box-right{ 
  justify-content:flex-end;
}

.main .container .box-section.box-left{ 
  justify-content:flex-start; 
}



.main .container .box-section.box-right .box{ 
  justify-content:flex-end;
  width:150px; 
  height:100%;  
  background:#0095ff;
}

.main .container .box-section.box-left .box{ 
  justify-content:flex-start; 
  width:120px; 
  height:100%;
  position:relative;
  background:#0095ff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
  <div class="header">
       <span> Main title here</span>
  </div>
  <div class="container">
      <div class="box-section box-right">
        <div class="box" id="box-left"></div>
      </div>
      <div class="box-section box-left">
        <div class="box"></div>
      </div>
  </div>
</div>