Left, right and center align the child div under the parent div container

I want to align the child Div under my parent Div based on its class on the 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>
Run codeHide result

I can not align child Divs with the center to the parent Divs. Can anyone help me with this?

+4
source share
3 answers

Just highlight text-align: center for the div container. JS fiddle - https://jsfiddle.net/72aqsq83/1/

.container{
  border:1px solid;
  padding:1px;
  width:100%;
  margin:1px;
  text-align:center
}
+5
source

I think you should use flexboxbox properties. This will probably solve your problem:

.container {
    display: flex;
    flex-flow: row wrap;
    justify-content: space-around;
}

Flexbox, , :
MDN - CSS
MDN -
MDN - -

CSS :
CanIUse - "flexbox"

+1

The easiest way to split a field into left, center, and right is with CSS flexbox. By wrapping left, center and right in the new one divand turning your container into flexbox with display:flex, you can 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>
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1669675/


All Articles