Left and Right Alignment using the float Property in CSS

We can align elements in HTML using the CSS float property that is used for positioning or formatting a box or content. You can position element towards left or right with CSS float. The float property can have any of the following values −

  • left − element float to the left

  • right − element floats to the right

  • none − element won?t float

Float right and left

Let?s see an example of CSS float property to align elements. Here, we have floated a container left using the float property with the value left and right using the value right −

.leftFloat{
   float: left;
}
.rightFloat{
   float: right;
}

Example

Let us see the example −

<!DOCTYPE html>
<html>
<head>
   <title>Alignment using CSS Float</title>
   <style>
      .screen {
         padding: 10px;
         width: 70%;
         margin: 0 auto;
         background-color: #f06d06;
         text-align: center;
         color: white;
         border-radius: 0 0 50px 50px;
         border: 4px solid #000;
      }
      .backSeats div{
         margin: 10px;
         padding: 10px;
         color: white;
         border: 4px solid #000;
      }
      .backSeats div {
         background-color: #4CAF50;
      }
      .leftFloat{
         float: left;
      }
      .rightFloat{
         float: right;
      }
   </style>
</head>
<body>
   <div class="screen">Screen</div>
   <div class="backSeats">
      <div class="leftFloat">Premium Left Seat 1</div>
      <div class="leftFloat">Premium Left Seat 2</div>
      <div class="rightFloat">Premium Right Seat 1</div>
   </div>
</body>
</html>

Float left and none

Let?s see another example of CSS float property to align elements. Here, we have floated a container left using the float property with the value left and no float using the value none −

p {
   float: left;
   margin: 10px;
   padding: 10px;
   color:white;
   background-color: #48C9B0;
   border: 4px solid #145A32;
}
p.noneFloat{
   float: none;
   clear: both;
   color: #34495E;
}

Example

Let us see the example −

<!DOCTYPE html>
<html>
<head>
   <title>Alignment using CSS Float</title>
   <style type="text/css">
      p {
         float: left;
         margin: 10px;
         padding: 10px;
         color:white;
         background-color: #48C9B0;
         border: 4px solid #145A32;
      }
      p.noneFloat{
         float: none;
         clear: both;
         color: #34495E;
      }
   </style>
</head>
<body>
   <p>I love Java.</p>
   <p class="noneFloat">I think C# is better.</p>
   <p>Even C isn't a bad choice.</p>
   <p>I agree!</p>
</body>
</html>
Updated on: 2023-12-26T15:04:36+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements