ab11
ab11

Reputation: 20090

Smart way to make divs the same size with css?

I have two different divs with various contents, and would like them to be the same height and width. It seems like a bad idea to set their height and width to a fixed pixel size, because their size should probably vary based on browser/screen size. Setting their width to a percentage works, but percentage is not an option for height.

Is there a way to ensure two divs have the same dimensions without setting to fixed pixel sizes? Or are fixed pixel sizes really so bad?

Upvotes: 6

Views: 2770

Answers (5)

user1389087
user1389087

Reputation:

I'd suggest defining a container div which varies according to screen width (using @media screen) and using css3's flex to define your divs like so :

HTML

<div class="container">
<div class="first-div">first div </div>
<div class="second-div">second div </div>
</div>

CSS

.first-div{
   -webkit-flex: 1; /* Safari 6.1+ */
   flex: 1;
    background-color:yellow;
   border: 2px solid black; 
}

.second-div{
    -webkit-flex: 1; /* Safari 6.1+ */
   flex: 1;
    background-color:blue;
     border: 2px solid black;  
}
.container{
    width:auto; 
    display: -webkit-flex; /* Safari */
    -webkit-align-items: center; /* Safari 7.0+ */
    display: flex;
    align-items: center;
}

https://jsfiddle.net/sujy3bq4/19/

Hope this helps you.

Upvotes: 1

Anne Gray
Anne Gray

Reputation: 89

Super easy and intuitive way to make responsive, square containers
Scalable percentage heights with padding-bottom:

See Codepen

Basically, set the height to 0, and set the bottom padding to any percentage you'd like.

.box {
  float: left;
  width: 23%;
  height: 0;
  padding-bottom:23%;
  margin: 1%;
  background-color: #e6e6e6;
  box-sizing: border-box;
  text-align: center;
}
<section>
  <div class="box">
    1
  </div>
  <div class="box">
    2
  </div>
  <div class="box">
    3
  </div>
  <div class="box">
    4
  </div>
</section>

Upvotes: 0

Vini
Vini

Reputation: 8419

If using CSS3 is an option in your case then you can use the 'ViewPort Percentage Lengths" Details on W3.

Something like below should work. (Refer question here for more details.)

div {
    height:100vh;
}

Upvotes: 0

Samuel Cook
Samuel Cook

Reputation: 16828

When using height, you need to make sure that you have a full body to work with. By default, the body height is auto. If you set the height to 100%, you can start to use the height attribute on child elements.

Just remember that height is always set to it's parent:

body,html{height:100%;}
div{width:50%; height:50%;}
.el1{float:left; background:#f00;}
.el2{float:right; background:#0f0;}
<div class="el1"></div>
<div class="el2"></div>

Upvotes: 0

lucasnadalutti
lucasnadalutti

Reputation: 5948

Having an outer div with display: table; and these two divs inside it with display: table-cell; should work for you.

Upvotes: 3

Related Questions