optimizitor
optimizitor

Reputation: 907

Make element fit page scroll width with CSS

I have a header with width: 100% and I want to make it automatically adjustable not only to screen width, but to page full width that can be stretched beyond screen width by other elements. I can do it with JS, but I wonder if it is possible to use pure CSS to achieve this.

In the example below the A block is intended to be the same size as the B block, but it is much shorter on small screens (just scroll everything to the right and you can see).

html,body{
  position:relative; width:100%;
}
#A{
  position:relative; width:100%;
  background:lightblue; color:white;
}
#B{
  position:relative; width:5000px;
  background:darkblue; color:white;
}
<html>
<head></head>
<body>
<div id="A">A</div>
<div id="B">B</div>
</body>
</html>

Any ideas?

Upvotes: 1

Views: 1910

Answers (4)

Yosef Tukachinsky
Yosef Tukachinsky

Reputation: 5895

	html,
		body {
			position: relative;
			width: 100%;
		}
		
		#B {
			position: absolute;
			width: 100%;
			top: 100%;
			left: 0;
			background: lightblue;
			color: white;
		}
		
		#A {
			position: relative;
			width: 5000px;
			background: darkblue;
			color: white;
            min-width:100%;
		}
	<div id="A"><div id="B">B</div>A</div>

Upvotes: 1

Jim
Jim

Reputation: 743

If you wrap the two divs (A & B) inside another you can achieve this.

html,body{
position:relative; width:100%;
}
#A{
position:relative; width:100%;
background:lightblue; color:white;
}
#B{
position:relative; width:5000px;
background:darkblue; color:white;
}
.header-wrap { display: inline-block; }
<html>

<head></head>

<body>
<div class="header-wrap">
<div id="A">A</div>
<div id="B">B</div>
</div>
</body>

</html>

Upvotes: 2

NightPorter
NightPorter

Reputation: 171

Try giving your A div a max-width of 5000px as well as width:100%

#A{
 position:relative; 
 width:100%;
 max-width:5000px;
 background:lightblue; 
 color:white;
}

Upvotes: 0

sol
sol

Reputation: 22919

You can try adding display: grid to the container, in this case body

body {
  display: grid;
}

#A {
  background: lightblue;
  color: white;
}

#B {
  position: relative;
  width: 5000px;
  background: darkblue;
  color: white;
}
<html>

<head></head>

<body>
  <div id="A">A</div>
  <div id="B">B</div>
</body>

</html>

Upvotes: 3

Related Questions