HTML / CSS - element weight

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

I do not mean font-weight. I mean the size that the element can stretch.

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

In this example, the first div should occupy 1/3 of the width or height (depending on the display property of the shell and its content orientation), since the sum of the weights of the elements in the wrapper is 3, and the weight of the div is 1. Therefore, the second div should occupy 2 / 3 spaces (weight = 2).

This is a great way to set the width of elements in a wrapper if one width is relative to the others and if their number is dynamic.

Is there something similar, or do I need to use JS for this?

+4
source share
3 answers

You can try display: flex;wrappers and property flexfor <div>s child . It should work the way you describe "weight."

flex: <positive-number>

Equivalent flex: <positive-number> 1 0px. This makes the flex element flexible and sets the base flexibility to zero, resulting in an element that gets the specified proportion of the remaining space.

If all elements in the flex container use this template, their sizes will be proportional to the specified coefficient of flexibility.

- CSS tricks aboutflex

.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>
Run codeHide result
+10
source

If you don't want to write your own CSS, there are CSS frameworks and libraries that will provide you with this functionality. Here is an example of 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>
Run codeHide result
+1

Flexbox "" /. : https://css-tricks.com/snippets/css/a-guide-to-flexbox/

By setting the second value flex-grow: 2, and the first - flex-grow: 1, you will get twice as much as the second, or 2/3 and 1/3.

* {
  box-sizing: border-box;
}

.wrapper {
  display: flex;
}
.weighed {
  height: 50px;
  border: 5px solid white;
}

.weight1 {
  flex: 1;
  background: green;
}

.weight2 {
  flex: 2;
  background: red;
}
<div class="wrapper">
  <div class="weighed weight1"></div>
  <div class="weighed weight2"></div>
</div>
Run codeHide result
+1
source

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


All Articles