1

I have a html web page which contains a responsive side bar (width of side bar changes on hover). I want the main content to have a margin relative to the width of the sidebar. Please help me how to achieve this using css> For example:

before hovering over the sidebar:

enter image description here

After hovering over the sidebar: enter image description here

Pavan
  • 381
  • 1
  • 4
  • 19
  • 2
    Does this answer your question? [How to set the margin or padding as percentage of height of parent container?](https://stackoverflow.com/questions/4982480/how-to-set-the-margin-or-padding-as-percentage-of-height-of-parent-container) – Fabian S. Oct 26 '21 at 05:17
  • it is not the height.. I want it based on the width – Pavan Oct 26 '21 at 05:26
  • That article covers both, width and height relative to its parents dimensions. Specifically https://stackoverflow.com/a/53618089/4218046. – Fabian S. Oct 26 '21 at 05:47

1 Answers1

0

By your photo example, I'm guessing you mean the width instead of margin, and you just want to make sure the divs don't overlap.

You can use flexbox, so that the .content element takes the remaining width when the .sidebar width changes. You can then set the .sidebar starting width, then change the width on hover.

Here's an example:

/* For style */
.sidebar span,
.content span {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  font-family: sans-serif;
}
.sidebar {
  background: #4C559F;
  cursor: pointer;
}
.content {
  background: #4F9DD4;
}
.sidebar,
.content {
  position: relative;
  transition: width 0.1s;
}

/* Important */
.container {
  height: 200px;
  display: flex;
  flex-direction: row;
}

.sidebar {
  width: 20%;
  margin-right: 10px; /* Your set margin */
}
.sidebar:hover {
  width: 40%;
}
.content {
  flex-grow: 1;
}
<div class="container">

  <div class="sidebar"><span>sidebar</span></div>
  <div class="content"><span>content</span></div>
  
</div>

However, if you want to move the content element over using margin. . . you will have to use javascript to add a class to the container or body element when you hover the sidebar. . . then style the container's margin to the needed size. . . orrr dynamically calculate it using javascript.

Hope this helps. God bless!

Charves
  • 36
  • 4