简体   繁体   中英

How to align all left floated elements in center of their parent?

 .container{width:50%;padding:10px;box-sizing:border-box;background-color:#00FF00;} .container::after {content: ''; display: table; clear: both;} .child{width:100px;height:30px;line-height:30px;text-align:center;border-radius:2px;background-color:#FFFF00;float:left;margin:2px;}
 <div class="container"> <div class="child">First</div> <div class="child">Second</div> <div class="child">Third</div> <div class="child">Fourth</div> </div>

I want to align the content of .container in center without using property display: inline-block; on .child .

see here : jsfiddle

EDITED : use display:flex with justify-content:center on the .sub-container and display:inline-block to .child

or you could use float:left on .child , it still works. but i suggest you don't use float when you want to center smth

code :

.child
{
  width: 50px;
  height: 30px;
  text-align: center;
  border-radius: 10px;
  background-color: #FFFF00;
  display:inline-block;
}

.sub-container
{
  width: 50%;
  height: auto;
  padding: 10px;
  box-sizing: border-box;
  margin: 0px auto;
  background-color: #00FF00;
  float: left;
  text-align: center;
  position:relative;
  display: flex;
  justify-content: center;
}

let me know if this was what you were looking for

Add to .main-container { margin: 0 auto; display: table; } .main-container { margin: 0 auto; display: table; } .main-container { margin: 0 auto; display: table; } and remove width:100%;

Maybe this can help you: Add margin 50% - half the width of the container. Just a disclaimer: this is not supported in some of the browsers.

.child {
  width: 100px;
  height: 30px;
  margin-left: calc(50% - 50px);
  text-align: center;
  border-radius: 10px;
  background-color: #FFFF00;
  float: left;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM