Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML / CSS - element's weight

Tags:

html

css

I'm wondering if there is some kind of weight property in HTML or CSS (or at least a work around).

I do NOT mean the font-weight. I mean the size an element can stretch to.

<div id="wrapper">
  <div weight="1">
  <div weight="2">
</div>

In this example the first div should take 1/3 of the width or height (depending on the wrapper's display property and its content's orientation) because the sum of the elements' weight in the wrapper is 3, and the div's weight is 1. Therefore the second div should take 2/3 of the space (weight = 2).

This would be a great way to set the width of elements in a wrapper, if one's width would be relative to the others' ones, and if their amount if dynamic.

Does something like this exist, or do I need to use JS for this?

like image 312
Froxx Avatar asked Feb 10 '17 18:02

Froxx


2 Answers

You can try display: flex; on the wrapper and the flex property on the child <div>s. It should work like you describe the "weight".

flex: <positive-number>

Equivalent to flex: <positive-number> 1 0px. It makes the flex item flexible and sets the flex basis to zero, resulting in an item that receives the specified proportion of the remaining space.

If all items in the flex container use this pattern, their sizes will be proportional to the specified flex factor.

— CSS-tricks about flex

.wrapper {
  display: flex;
}
.wrapper div {
  border: 1px solid black;
}
.wrapper div:first-child {
  flex: 1;
}
.wrapper div:nth-child(2) {
  flex: 2;
}
<div class="wrapper">
  <div>test</div>
  <div>test</div>
</div>
like image 165
andreas Avatar answered Oct 09 '22 22:10

andreas


If you don't want to write your own CSS, there are CSS frameworks and libraries that will give you this functionality. Here's an example using bootstrap

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row">
    <div class="col-sm-4">1</div>
    <div class="col-sm-8">2</div>
  </div>
</div>
like image 34
Michael Coker Avatar answered Oct 09 '22 22:10

Michael Coker