将文本与第一个左侧块对齐

时间:2016-02-27 10:27:12

标签: css alignment css-float flexbox

我想将文本与第一个左侧块对齐。块与中间对齐。更改屏幕/浏览器宽度时,应调整文本。

怎么做才能得到这个:

enter image description here

在IE中可以吗?

#container {
  border: 1px solid gray;
}
.outerBlock {
    border: 1px solid red;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}
.block {
  width: 150px;
  height: 150px;
  background-color: #cccccc;
  margin: 10px;
}
<div id="container">
  Aligned left to first block
  <div class="outerBlock">  
    <div class="block">1</div>    
    <div class="block">2</div>    
    <div class="block">3</div>    
    <div class="block">4</div>    
    <div class="block">5</div>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

使用flexbox执行此操作的唯一方法是将框设置为justify-content: space-between;。然后在顶部给出10px左边距的文本:

#container {
    border: 1px solid gray;
}

#container span{
	margin-left:10px;
}

.outerBlock {
    border: 1px solid red;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}

.block {
    width: 150px;
    height: 150px;
    background-color: #cccccc;
    margin: 10px;
}
<div id="container">
    <span>Aligned left to first block</span>
    <div class="outerBlock">
        <div class="block">1</div>
        <div class="block">2</div>
        <div class="block">3</div>
        <div class="block">4</div>
        <div class="block">5</div>
    </div>
</div>

更新:定位于jQuery

var el = $('.outerBlock > .block');
var os = el.offset();

$('.blockText').css("margin-left",os.left - parseInt(el.css('margin-left')));
*{
  box-sizing:border-box;
}

#container {
    border: 1px solid gray;
}

.outerText {
    border: 1px solid red;
}

.outerBlock {
    border: 1px solid red;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}

.block {
    width: 150px;
    height: 150px;
    background-color: #cccccc;
    margin: 10px;
}
.blockText {
    width: 150px;
    max-height: 20px;
    margin: 0 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
    <div class="outerText">
      <div class="blockText">News</div> 
    </div>
    
    <div class="outerBlock">
        <div class="block">1</div>
        <div class="block">2</div>
        <div class="block">3</div>
        <div class="block">4</div>
        <div class="block">5</div>
    </div>
</div>