vertically aligning something with flexbox

时间:2018-02-26 17:44:24

标签: css flexbox

Coding a simple notification list with flexbox profile picture on the left, description on the top left of the picture with a timestamp on the bottom of the desc.

I can't get the span to vertically align to the bottom.

I know it must be something simple. Also, is this the best way of doing something like this with flexbox? eg. using a ul

* {
            margin: 0;
            padding: 0;
        }
    
        ul li {
            display: flex;
            flex-direction: row;
        }
    
        ul li img {
            padding-right: 15px;
        }
    
        ul li div {
           display: flex;
           flex-direction: column;
        }
    
        ul li div p {
           vertical-align: top;
        }
    
        ul li div span {
           vertical-align: bottom;
        }
<ul>
         <li>
            <img style="width: 50px; height: 50px;" />
              <div>
               <p>some thing</p>
               <span>timestamp</span>
           </div>
        </li>
    </ul>
    
        

https://jsfiddle.net/s3jnLmxy/9/

2 个答案:

答案 0 :(得分:1)

Just add margin top auto to the span and you can remove the vertical align rules - ul li div p is removed

* {
  margin: 0;
  padding: 0;
}

ul li {
  display: flex;
  flex-direction: row;
  background: green
}

ul li img {
  padding-right: 15px;
}

ul li div {
  display: flex;
  flex-direction: column;
  background: gray;
}

ul li div span {
  margin-top: auto;
}
<ul>
  <li>
    <img style="width: 50px; height: 50px;" />
    <div>
      <p>some thing</p>
      <span>timestamp</span>
    </div>
  </li>
</ul>

For completeness I will add the other solution as well

Add justify-content: space-between; to the flex container (div). This will work in this particular situation however depending on your content (different than current) this may not work.

答案 1 :(得分:1)

Reusing your code, only need to change the ul li div rule and then, there is not need for the final two: ul li div p and ul li div span:

ul li div {
  display: flex;
  flex-direction: column;
  justify-content: space-between; /* added line */
}

More info about justify-content property here


* {
  margin: 0;
  padding: 0;
}

ul li {
  display: flex;
  flex-direction: row;
}

ul li img {
  padding-right: 15px;
}

ul li div {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
<ul>
  <li>
    <img style="width: 50px; height: 50px;" />
    <div>
      <p>some thing</p>
      <span>timestamp</span>
    </div>
  </li>
</ul>