How to resize circle div dynamically?

45 views Asked by At

Circle should take all available container height and depend on it. Circle width should be the same as height. How to make circle width depend on height? Current behavior:

.container {
  width: 300px;
  height: 150px;
  border: 1px solid black;
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 20px;
  padding: 20px;
}

.circle {
  height: 100%;
  border-radius: 50%;
  background-color: green;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="container">
  <div class="circle">
    i
  </div>
  <div>
    Text
  </div>
</div>

Needed behavior (width & height shouldn't be hardcoded):

enter image description here

If container height changes it should influence circle height & width too

2

There are 2 answers

0
Jerry On

You can use aspect-ratio: 1 / 1; property, which is now supported in all major browsers.
Also check original aswer.

.container {
  width: 300px;
  height: 150px;
  border: 1px solid black;
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 20px;
  padding: 20px;
}

.circle {
  height: 100%;
  aspect-ratio: 1 / 1;
  border-radius: 50%;
  background-color: green;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="container">
  <div class="circle">
    i
  </div>
  <div>
    Text
  </div>
</div>

0
Yuvaraj M On

You can use flex-basic to set initial main size for .circle.

.container {
  width: 300px;
  height: 150px;
  border: 1px solid black;
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 20px;
  padding: 20px;
}

.circle {
  height: 100%;
  border-radius: 50%;
  background-color: green;
  flex-basis: 50%;
  display: grid;
  align-items: center;
  justify-content: center;
}
<div class="container">
  <div class="circle">
    i
  </div>
  <div class='text'>
    Text
  </div>
</div>