Skip to content Skip to sidebar Skip to footer

Set Width Of Fixed Div Equal To That Of Parent Width (which Is Declared As Percentage)

I want to have the width of a position: fixed div (because I want it to be able independently of page scrolling) equal to the width of its parent ( a td element ). However I cannot

Solution 1:

You can have what you want by replacing fixed with sticky but it will work perfectly in case the table is your only element as sticky position will not make the element to be fixed outside his containing block (parent element)

table {
  border: 1px solid black;
  width: 90%;
}

#tdLeft,
#tdRight {
  margin: 0;
  padding: 0;
  border-spacing: 0px;
  border-collapse: collapse;
  vertical-align: top;
}

#tdLeft {
  position: relative;
  width: 50%;
}

#tdRight {
  position: relative;
  width: 50%;
  background-color: green;
}

#divFixed {
  position: sticky;
  border: 1px solid black;
  top: 100px;
}
<table><tr><tdid="tdLeft">
      fdsfsdfsd<br><br><br><br><br><br><br><br><br>
      fdsfsdfsd<br><br><br><br><br><br><br><br><br>
      fdsfsdfsd<br><br><br><br><br><br><br><br><br>
      fdsfsdfsd<br><br><br><br><br><br><br><br><br>
      fdsfsdfsd<br><br><br><br><br><br><br><br><br></td><tdid="tdRight">
      fdsfsd
      <br>
      rfeoif jerofj eriof
      <divid="divFixed">
        hahaha, fdsfsd, fsdfsd, fdsfds, fdsfaaasd, fdfsdss, 
        hahaha, fdsfsd, fsdfsd, fdsfds, fdsfsd, fdfsd, 
        hahaha, fdsfsd, fsdfsd, fdsfds, fdsfsd, fdfsd
      </div></td></tr></table>

Solution 2:

Use position: sticky instead of fixed:

The element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related elements, based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements.

Source: MDN

See demo below:

#tdLeft, #tdRight {
	margin: 0;
	padding: 0;
	border-spacing: 0px;
	border-collapse: collapse;
	vertical-align: top;
}
#tdLeft {
  position: relative;
  width: 50%;
}
#tdRight {
  position: relative;
  width: 50%;
  background-color: green; 
}
#divFixed {
	position: sticky; /* CHANGED */border: 1px solid black;
	top: 100px;
	/*width: inherit;*/
}
<tablestyle="width: 90%; border: 1px solid black;"><tr><tdid='tdLeft'>
  fdsfsdfsd<br><br><br><br><br><br><br><br><br>
  fdsfsdfsd<br><br><br><br><br><br><br><br><br>
  fdsfsdfsd<br><br><br><br><br><br><br><br><br>
  fdsfsdfsd<br><br><br><br><br><br><br><br><br>
  fdsfsdfsd<br><br><br><br><br><br><br><br><br></td><tdid='tdRight'>
    fdsfsd
    <br>
    rfeoif jerofj eriof
    <divid='divFixed'>
      hahaha, fdsfsd, fsdfsd, fdsfds, fdsfaaasd, fdfsdss, 
      hahaha, fdsfsd, fsdfsd, fdsfds, fdsfsd, fdfsd, 
      hahaha, fdsfsd, fsdfsd, fdsfds, fdsfsd, fdfsd
    </div></td></tr></table>

Post a Comment for "Set Width Of Fixed Div Equal To That Of Parent Width (which Is Declared As Percentage)"