It's not the first time it happens and I have never found a good explanation.
In this particular case, I have an h3 and a p inside a div. As soon as I changed the p's width, the h3's width changed as well, like as the width was being applied to their parent.
- Why does this happen?
and
- I found that the fix (or at least one of the fixes) in my case, was to apply
display: inline-blockto theh3. If you remove it, you'll see that the button takes the paragraph's width of95vw. How come does this work?
Thank you
let button = document.querySelector('.button')
let body = document.querySelector('.body')
let container = document.querySelector('.container')
button.addEventListener('click', ()=> {
let colorOne = parseInt((Math.random() * 255) + 1)
let colorTwo = parseInt((Math.random() * 255) + 1)
let colorThree = parseInt((Math.random() * 255) + 1)
let colorOneOne = parseInt((Math.random() * 255) + 1)
let colorTwoTwo = parseInt((Math.random() * 255) + 1)
let colorThreeThree = parseInt((Math.random() * 255) + 1)
let deg = parseInt((Math.random() * 360) + 1)
body.style.background = 'linear-gradient(' + deg + 'deg' + ', ' + 'rgb(' + colorOne + ', ' + colorTwo + ', ' + colorThree + ')' + ',' + 'rgb(' + colorOneOne + ',' + colorTwoTwo + ',' + colorThreeThree + '))'
//linear-gradient(45deg, rgb(28,28,84), rgb(38,58,119))
document.querySelector('.color').innerText = 'linear-gradient(' + deg + 'deg' + ', ' + 'rgb(' + colorOne + ', ' + colorTwo + ', ' + colorThree + ')' + ',' + 'rgb(' + colorOneOne + ',' + colorTwoTwo + ',' + colorThreeThree + '))'
button.style.border = 'none'
document.querySelector('.scrollto').style.display = 'block'
})
window.addEventListener('touchmove', ()=> {
body.style.background = 'white'
document.querySelector('.color').innerText = ''
document.querySelector('.scrollto').style.display = 'none'
button.style.border = '1px solid black'
})
.button {
font-family: 'Poppins', sans-serif;
border-radius: .5em;
padding: .3em .7em;
font-size: 1.1em;
position: relative;
background: white;
mix-blend-mode: screen;
border: 1px solid black;
display: inline-block;
}
@media screen and (max-width: 382px) {
.button {
width: 10em;
}
}
body {
min-height: 100vh;
margin: 0;
}
.color {
font-family: 'Poppins', sans-serif;
color: white;
text-shadow: 1px 1px 3px black;
letter-spacing: 1px;
display: block;
width: 95vw;
border: 2px solid black;
}
.container {
text-align: center;
position: absolute;
top: 40vh;
left: 50vw;
transform: translate(-50%, -50%);
}
.scrollto {
position: absolute;
bottom: 10px;
left: 50vw;
transform: translateX(-50%);
font-family: 'Poppins', sans-serif;
font-size: .7em;
display: none;
}
<body class="body">
<div class="container">
<h3 class="button">Generate Gradient</h3>
<p class="color"></p>
</div>
<div class="line">
<p class="scrollto">swipe on screen to reset</p>
</div>