Skip to content

Instantly share code, notes, and snippets.

@yi-mei-wang
Last active September 30, 2019 02:43
Show Gist options
  • Save yi-mei-wang/cce2015d4303ab9d61522a298be9f016 to your computer and use it in GitHub Desktop.
Save yi-mei-wang/cce2015d4303ab9d61522a298be9f016 to your computer and use it in GitHub Desktop.
Responsive width and height

Responsive width and height

Using % as width and height values

  • Ensure that you know what you are using % relative to

  • % is usually relative to the parent

  • Let's see some code!

    <div class="image-wrapper">
       <img src="image.png" alt="Example" id="sample-image"/>
    </div>
    
    .image-wrapper {
     width: 500px;
    }
    
    #sample-image {
    // This means that the image will be 50% of the parent, i.e., 50% * 500px = 250px
    width: 50%;
    }
    

Using vw and vh as width and height values

  • Sometimes we want our elements to take up the full width/height of the document

  • We can do so with vw and vh

    .image-wrapper {
     // This will ensure the container takes up the entire width of the screen
     width: 100vw;
    }
    

Using calc to calculate width and height values

  • Sometimes we want our elements to take up the space remaining after taking into account other elements
    #content {
       height: calc(100vh - 70px - 70px);
    }
    

Using min- and max-

  • We use min-width/min-height when we want to ensure that the element takes up at least a certain height
  • e.g. without min-width
  • with min-width
  • Look at the example code (HTML and CSS) below
body {
margin: 0;
}
#navbar {
height: 70px;
background-color: rgb(216, 149, 149);
}
#content {
height: calc(100vh - 70px - 70px);
min-height: 500px;
background-color: rgb(252, 252, 126);
}
#footer {
height: 70px;
background-color: rgb(165, 165, 252);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="demo.css" />
<title>Document</title>
</head>
<body>
<nav id="navbar"></nav>
<section id="content"></section>
<footer id="footer"></footer>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment