0

I am trying to figure out how to solve the following problem with CSS:

I have a container, say it's a div. It should be always visible on my page, vertically and horizontally centered. The container should not have a fixed size, but a fixed proportion (or aspect ratio), say: "width = 1/3 of height". Moreover, the container should be always visible as huge as possible. (Meaning either "touch" the upper and lower OR the left and right borders of the browser window, depending on the current window size)

This is how I proceeded so far:

relevant html:

<body>
    <div>Text</div>
</body>

css:

body {
   margin: 0px;
}

div {
   position: absolute;
   background-color: red;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}

This of course only centers the div. The cucial part is the sizing, that I described above. Would this be possible with css?

Anton Harald
  • 5,772
  • 4
  • 27
  • 61

2 Answers2

1

You can set min-height: 100vh so element will always be full height and width: calc(100vh/3); so width is 1/3 of window height

Demo

body {
   margin: 0px;
}

div {
   position: absolute;
   background-color: red;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
   min-height: 100vh;
   width: calc(100vh/3);
}
<div>Text</div>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • cool, goes in the right direction. but is not yet exactly what I need. Let's use the proportion (width = 0.8 * height) for testing. So I resize the window vertically: After the point the window has the same size as the box, I get scrollbars - which I want to avoid. In this case I'd like the div to shrink and see whitespace above and below it. – Anton Harald Dec 22 '15 at 18:45
  • You can change `width` with media queries. – Nenad Vracar Dec 22 '15 at 18:51
-1

This is a version of the responsive video solution. You'll need to wrap the element you want to keep the ratio for in a container.

#container{
    position:relative;
    padding-top:33%;
    width:100%;
}

#container div{
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    width:100%;
    height:100%;
}

Padding (and margin) percentages are based on the width of the element. So, if the width is 100%, the height in the above code will be 1/3 of the width (33%).

Donnie D'Amato
  • 3,832
  • 1
  • 15
  • 40
  • Yes. If you want height, you'll have to use the `vh` units which are only relative to the viewport height or use javascript to calculate the ratios. – Donnie D'Amato Dec 22 '15 at 19:05
  • yes, this is width only. I want to avoid the JS solution, if possible. could you show an example with the vh units? – Anton Harald Dec 22 '15 at 19:10
  • @fauxserious At least currently this does not answer the question, as it is width-only. – Roope Dec 22 '15 at 21:11
  • `The container should not have a fixed size, but a fixed proportion (or aspect ratio), say: "width = 1/3 of height"` – Donnie D'Amato Dec 23 '15 at 01:07