Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

html - How does width/height get calculated on position:absolute container with text in it and width:auto;height:auto?

The following example shows a position:absolute element centered on screen, with width:auto and height:auto, yet it has some particular width to height ratio of approximately 2.909090909090909 no matter what size your viewport is.

How is this constant ratio determined?

body,
html {
width: 100%;
height: 100%;
margin: 0;
}

div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 3vw;
font-family: sans-serif;
background: pink;
width: auto; height: auto
}
<div>
You are in! The pill you took is part of a trace program. It's designed to disrupt your input/output carrier signal so we can pinpoint your location.
</div>
question from:https://stackoverflow.com/questions/65944148/how-does-width-height-get-calculated-on-positionabsolute-container-with-text-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If we turn off top and transform, this is how it looks:

enter image description here

Then, the block is moved to the center (using those top and transform), but its width is determined by the "squeeze" caused by left (remember that it's a div, so by default it wants to be 100% of the parent's width).

It means that the amount of "squeezing" is dependent on the screen width.

The thing is font-size is also dependent on the screen width: 3vw.

Since both the box's width and the font size is calculated by the width of the container (which is in this case, the same size as the viewport itself), you get that constant size.

If you had a constant font size, let's say of 2rem, this is how it will look:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...