Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css width same as height

Tags:

html

css

I would like to do the next trick in my css file so that (height = width) without setting pixels. I want to do this so whatever the resolution of the browser is, to have same values on these two dimensions.

#test{
    height: 100%;
    width: (same as height);
}

I prefer to do it with css and not javascript.

Thank you in advance.

like image 972
giorgos Avatar asked Feb 15 '14 15:02

giorgos


People also ask

Is width and height same?

The length, width and height are the dimensions of a geometrical figure that depict how long, wide and high a figure is. While length is the longest side of a figure, width is the shorter side and height is the vertical dimension of the figure.

How set dynamic width and height in CSS?

Top header with 100% width and 50px height. Left navigation bar with 200px width and dynamic height to fill the screen. A container on the right of the nav bar and under the header with dynamic width and height to fill the screen.

How do I keep aspect ratio in CSS?

In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.


2 Answers

This is my way

  aspect-ratio: 1 / 1;
  height: 100%;

Example:

.my-container {
  width: 100%;
  height: 150px;
  background: black;
  padding: 20px
}

.my-element {
  background: #fff;
  aspect-ratio: 1 / 1;
  height: 100%;
}
<div class="my-container">
  <div class="my-element">Height = Width</div>
</div>
like image 75
Paulo Rosa Avatar answered Oct 18 '22 07:10

Paulo Rosa


The only CSS way of doing this at the moment (AFAIK) is using viewport relates values (vh / vw )

Support is not great at the moment: http://caniuse.com/viewport-units but here is a quick demo

JSFiddle

CSS

.box {
    background-color: #00f;
    width: 50vw;
    height:50vw;
}

The box is responsive but will always remain square.

Pure % values will not work as height:100% does not equal width:100% as they refer to different things being the relevant dimensions of the parent.

like image 24
Paulie_D Avatar answered Oct 18 '22 09:10

Paulie_D