Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left, Right and Center Align Child div under Parent Div Container

Tags:

html

css

I want to align child Div under my Parent Div based on its class to left, right or Center.

I have done the following,

.container{
  border:1px solid;
  padding:1px;
  width:100%;
  margin:1px;
}

.left-item{
  float:left;
  padding:auto;
  margin:1px;
}

.center-item{  
   padding:auto;
  margin:1px;
 }

.right-item{
 float:right;
 padding:auto;
  margin:1px;
}
<div class="container">        
    <button class="left-item">Left</button> <button class="center-item">Center 2</button> <button class="right-item">Right</button> <button class="left-item">Left</button> <button class="right-item">Right</button> <button class="center-item">Center 1</button> <button class="center-item">Center 3</button>        
</div>

I am unable to align child Divs to center to parent Divs. Can any one help me with this?

like image 403
Jeet Avatar asked Feb 14 '17 09:02

Jeet


People also ask

How div align child div in center of parent?

To truly center the child div, you can set negative top and left margins. Each value should be exactly half the child element's height and width.

How do I align my child div horizontally?

We can set the child element as an in-line element, display: inline-block; , and then set the father element as text-align: center; , so that the child element can be horizontally centered.

How do I align a div to the right side?

Use CSS property to set the height and width of div and use display property to place div in side-by-side format. float:left; This property is used for those elements(div) that will float on left side. float:right; This property is used for those elements(div) that will float on right side.

How do you set a right and left div tag?

Using float and marginThe left div is styled with width:50% and float:left – this creates the green colored div that horizontally covers half of the screen. The right div is then set to margin-left:50% – this immediately places it to the right of the left div.


1 Answers

A simpler way to divide a box into left, center and right is using CSS flexbox. By wrapping left, center and right in a new div and turning your container into a flexbox with display:flex you are able to emulate this behavior with much less code.

.container {
  border: 1px solid;
  padding: 1px;
  width: 100%;
  margin: 1px;
  display:flex;
  justify-content:space-between;
}
<div class="container">
  <div>
    <button>Left</button>
    <button>Left</button>
  </div>
  <div>
    <button>Center 2</button>
    <button>Center 1</button>
    <button>Center 3</button>
  </div>
  <div>
    <button>Right</button>
    <button>Right</button>
  </div>
</div>
like image 61
Dylan Stark Avatar answered Nov 03 '22 16:11

Dylan Stark