flex-box-self align

HOW TO ALIGN SELF USING FLEX BOX

If you have ever use the float property to align items left and right in a container, you will surely appreciate what flex box offer with simple content justification and alignment. One major advantage of the flex box is that, right from the parent element you can align all the items in the container, however, flex box still gives you the option to self align and justify the parent content, In essence, you can override the default value set in the parent container using the child element you which to self align.

Changing The Default Align Value Of a Single Item

This code below is just one way to align items using flex box.

HTML

  <body>

   <div class=”adder-comp”>

   <form>

    <input type=”text” placeholder=”aggiungi compito..” />

    <p>  some nice and long text of words goes here</p>

 <button>crea</button>

</form>

    </div>

  </body>

</html>

CSS

* {

  padding: 0;

  margin: 0;

  box-sizing: border-box;

}

form {

  width:80%;

margin: 0 auto;

margin-top:100px;

padding:20px;

  display: flex;

  background: orange;

  justify-content: space-between;

  align-items: center;

}

center+aligned+flex+items
I

if you try your hand the code above, you notice all the items in the form are well aligned and justified as shown above, but for some reason, you may change your mind and want the input field at the left to appear at the baseline of the form. You can add this code below to achieve that.

form input {

  align-self: baseline;

}

 By adding the line of code above, you have succeeded in overriding the default align item value set at the parent

Let us make the example even more interesting. since most of the our html contents are rendered as box in our browser, let us use boxes to explain self align.

our aim is to design something like this

self aligned flex items

HTML

  <div class=”parent”>

      <div class=”start”>START</div>

      <div>CENTER</div>

      <div class=”flex-end”>END</div>

    </div>

CSS

.parent {

  width: 80%;

  margin: 0 auto;

  margin-top: 100px;

  padding: 20px;

  height: 300px;

  display: flex;

  background: orange;

  justify-content: space-between;

  align-items: center;

}

div {

  background-color: white;

  padding: 22px;

}

.start {

  align-self: flex-start;

}

.flex-end {

  align-self: flex-end;

}

Hopefully with the examples, you fully understand how to work with the align-self property in css

Leave a Comment

Your email address will not be published. Required fields are marked *