Languages
[Edit]
EN

CSS - how to align element to left and right with flex?

13 points
Created by:
Kate_C
2857

Using Flexbox it is possible to align child elements in few ways.

1. Spacer element between example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    .parent {
      	border: 1px solid red;
    	display: flex;
    }
    
    .child {
    	padding: 10px;
    }
    
    .left-child {
    	background: lightgreen;
      	flex: 0;
    }
    
    .spacer {
      	background: ivory;
    	flex: auto;
    }
    
    .right-child {
    	background: lightblue;
    	flex: 0;
    }
    
  </style>
</head>
<body>
  <div class="parent">
    <div class="child left-child">LEFT</div>
    <div class="child spacer">SPACER</div>
    <div class="child right-child">RIGHT</div>
  </div>
</body>
</html>

2. space-beetwen container style example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    .parent {
      	border: 1px solid red;
    	display: flex;
      	justify-content: space-between;
    }
    
    .child {
    	padding: 10px;
    }
    
    .left-child {
    	background: lightgreen;
      	flex: 0;
    }
    
    .right-child {
    	background: lightblue;
    	flex: 0;
    }
    
  </style>
</head>
<body>
  <div class="parent">
    <div class="child left-child">LEFT</div>
    <div class="child right-child">RIGHT</div>
  </div>
</body>
</html>

3. auto margin example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    .parent {
      	border: 1px solid red;
    	display: flex;
    }
    
    .child {
    	padding: 10px;
    }
    
    .left-child {
      	margin-right: auto;
    	background: lightgreen;
      	flex: 0;
    }
    
    .right-child {
      	/* margin-left: auto; */
    	background: lightblue;
    	flex: 0;
    }
    
  </style>
</head>
<body>
  <div class="parent">
    <div class="child left-child">LEFT</div>
    <div class="child right-child">RIGHT</div>
  </div>
</body>
</html>

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.