dbld
dbld

Reputation: 1097

How to make divs fill the width of its parent?

I want my divs(.give, .sep, .take) to fill its parent(.trade)'s width.

HTML code:

<div class="trade">
  <div class="give"></div>
  <div class="sep"></div>
  <div class="take"></div>
</div>

CSS code:

.trade {
  position: relative;
  width: 90%;
  height: 80px;
  border: 1px solid black;
}

.give,
.take {
  height: 100%;
  display: inline-block;
}
.sep {
  width: 20px;
  height: 100%;
  border-left: 1px solid black;
  border-right: 1px solid black;
  display: inline-block;
}

But, .give,.take{width:auto;} did not fill it.

I also tried:

.give,
.take {
  position:absolute;
  width:50%;
}
.sep {
  position:absolute;
  left:50%;
  transform:translate(-50%,0);
}
.give {
  left: 0;
}
.take {
  right: 0;
}

But .give and .take invaded .sep's place.

How can I make it? I don't want to use Javascript if possible.

+) .give{margin-right:10px;} .take{margin-left:10px;} or .give{padding-right:10px;} .take{padding-left:10px;} didn't work and just expanded their width.

Upvotes: 0

Views: 70

Answers (2)

Professor Abronsius
Professor Abronsius

Reputation: 33813

Is this the intended result? flexbox makes this fairly straightforward... The borders and the padding on .trade are for visual aid only

.trade{
  display:flex;
  flex-direction:row;
  justify-content:space-around;
  align-content:center;
  border:1px solid red;
  padding:1rem;
  margin:0 auto;
  float:none;
  
  width:80%;
  height:10rem;
}


.trade div{
  border:1px solid black;
  flex:1
}

.trade div:before{
  content:attr(class)
}
<div class="trade">
  <div class="give"></div>
  <div class="sep"></div>
  <div class="take"></div>
</div>

Upvotes: 1

tacoshy
tacoshy

Reputation: 13002

As said by G-Cyrillus, you shouldn't try to hack with float. inline-block is also completely unecessary and far to complicated for your purpose in this case.

The real tool is Flexbox. Add .trade { display: flex; } to the CSS to use flexbox.

Then you can use .give, .take { flex-grow: 1; } to make them extend to fill the entire parents width equally. Instead of using margins to seperate your 3 child elements, you can use .trade { column-gap: 20px; } instead.

.trade {
  position: relative;
  width: 90%;
  height: 80px;
  border: 1px solid black;
  display: flex;
  column-gap: 20px;
}

.sep {
  width: 20px;
}

.give,
.take {
  flex-grow: 1;
}

/* added for demonstration */

.trade {
  background-color: red;
}

.give,
.sep,
.take {
  background-color: blue;
}
<div class="trade">
  <div class="give"></div>
  <div class="sep"></div>
  <div class="take"></div>
</div>

Upvotes: 1

Related Questions