What makes vh effective while % falls short in terms of height CSS?

I frequently encounter an issue with my code where using % for height doesn't work, only vh does. It's strange why height has this problem while width can be set up with %. Here is the app component I am working on:

import MainPage from "./MainPage/MainPage";
import Headline from "./Headline/Headline";
import "./App.css";

function App() {
  return (
    <div className="App">
      <Headline />
      <MainPage />
    </div>
  );
}

Below is the CSS for the app component:

.App {
  height: 100%;
  width: 100%;
  text-align: center;
  background-color: white;
  display: flex;
  flex-direction: column;
}

The problem seems to arise in the Headline component. Let's take a look at it:

import "./Headline.css";

function Headline() {
  return (
    <div className="headline-container">
      <div className="headline">Cryprocurrency Tracker</div>
    </div>
  );
}

And here is the corresponding css for the Headline component:

.headline-container {
  height: 10vh;      --------> % doesn't work, I can change the height only with vh.
  width: 100%;       --------> width however doesn't have this problem at all.
  background-color: #0060ff;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  color: white;
  font-size: 30px;
  font-weight: 800;
  font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif;
}

.headline {
  height: 100%;
  width: 90%;
  display: flex;
}

Just in case, here is the CSS for the index file which only includes one child component - app:

body {
  height: 100vh;
  width: 100vw;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
    "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
    monospace;
}

Answer №1

Typically, elements will span the full width of the screen unless otherwise specified. For example, using width:50% would allocate half of the screen to your element if no other CSS rules override it.

Height, on the other hand, behaves differently. By default, an element's height is based on the content within it, not necessarily the full height of the screen.

To make an element take up the entire height of the screen, you can set its height to 100vh.

For instance:

<div class="text-wrapper">
   <p class="text">Lorem ipsum</p>
</div>

With this HTML structure, setting the height of .text to 100% won't have any visible effect since the default behavior is based on content height.

However, if you set the height to 100vh like this:

.text {
   height:100vh;
}

You'll force the element to fill the entire height of the screen.

The same concept applies when specifying the parent element as 100vh and the child as 100%, as shown below:

.text-wrapper {
   height:100vh;
}
.text {
   height:100%;
}

In this scenario, the wrapper takes up the full screen height, while the child element maximizes the available space within it.

Answer №2

When using percentages (%) in CSS for height, it's important to note that it is a relative unit and the resulting height will depend on the parent element's height.

For example, if we have a .container div with two parent elements: one being the `body` and the other being the browser window itself. Since the default value of the height property is set to auto, by setting both parent elements' heights to 100%, the .container div will inherit the height of the browser window at 100%.

Source

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8>
<title>Setting DIV Height to 100% with CSS</title>
<style>
    html, body {
        height: 100%;
        margin: 0px;
    }
    .container {
        height: 100%;
        background: #f0e68c;
    }
</style>
</head>
<body>
    <div class="container">The height of this DIV element matches the 100% height of its parent element.</div>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Revamping nearly indistinguishable elements within Formik React

Having two identical components with a few differences can lead to repetitive code and boilerplate. I'm unsure of the best way to refactor this so that I only need to provide a configuration. LoginPage.js import React from 'react&apo ...

What are some tips for troubleshooting a website on an iOS device?

What are the best methods for troubleshooting iOS websites? My website is not functioning correctly on iPhones as expected, unlike Firefox or Chrome on desktop. In order to identify the issue, I need to troubleshoot it. Are there similar tools like develo ...

How can we create an HTML Canvas that has no size limitations?

Greetings to all, I am currently engaged in a project involving the visualization of data on a colorful line. Imagine collecting 300 samples of sky color throughout the day, and plotting them on a line similar to this: https://i.sstatic.net/29IUN.png T ...

The installation of Google Maps in React was unsuccessful

I am trying to incorporate Google Maps into my app, but I encountered an issue while attempting to install it using the command npm install --save google-map-react. The error message displayed in the terminal is as follows: npm ERR! code ERESOLVE npm ERR! ...

Activate the 'li' element within the 'ul' whenever a 'ui-sref' link on the

I have been working on building a dashboard that consists of an abstract state called dashboard, with subdashboard as the immediate child state. https://i.sstatic.net/YTHky.png Previously, clicking on user details would take the user to the dashboard.tab ...

Customizing CSS input file for Firefox (also compatible with Chrome)

Currently, I am developing an upload page that does not allow the use of jquery and bootstrap. For Chrome, I have implemented the following CSS code to address my issue: .btn-file-upload{ width: 200px; position:relative; height: 40px; } .btn- ...

What is the best approach for identifying data types when transitioning from Javascript to Typescript?

Upon reviewing the tutorial at https://www.sitepoint.com/how-to-migrate-a-react-app-to-typescript/, I came across the following JavaScript code: import React from 'react' import { buttonStyles } from './Button.styles' const Button = ({ ...

Looking for assistance in using JavaScript to determine the percentage of a DIV's width in pixels

Using PHP, I am generating boxes whose width is set to 100% of a container in CSS. Now, I want to determine the equivalent pixel value of that box... HTML <div class="masonry" > <? while($row = $stmt->fetch()){ ?> <div class="i ...

What could be causing the CSS and HTML connection to fail?

I am currently working with Flask on the Atom editor to build a website. Despite specifying the correct path for the CSS file in the link, every time I load the page, it appears without any styling. I have attempted changing the paths multiple times with n ...

When switching tabs in Javascript, the page does not automatically reload. However, the page will reload only when it is on

After writing a code using javascript/Youtube API + PHP to fetch a YT video ID from a MySQL server and place it in Javascript, I realized that the page only reloads when the tab is active and not when it's in the background. This issue disrupts the wh ...

Encountered a hiccup when trying to deploy my NextJS App on Vercel, and I've got the Tail

I am currently facing issues while trying to deploy my NextJS App on Vercel. The errors that are appearing during deployment are quite perplexing, especially since I am also utilizing the Tailwind CSS framework. Identifying the root cause of the error has ...

Creating a responsive navigation menu by converting overflowing menu items into a dropdown list

I'm currently designing a menu that contains multiple list items. I would like the overflowing li's to collapse and display in a dropdown when resizing the browser to smaller screens, such as laptops and tablets. Original Menu. https://i.sstatic ...

Encountering a window undefined error while using React-leaflet

I'm currently working on creating a map using react-leaflet and server-side react. To tackle the "ReferenceError: window is not defined" issue, I've implemented a map component and experimented with utilizing the useEffect hook for dynamic loadin ...

Lifecycle events - The best place to initialize state?

I've been working on adding sorting functionality to my movie app. Initially, I had a working code but it suffered from a lot of code repetition. I want to refactor it to follow the DRY principle. However, I'm unsure about the best approach for s ...

Can JavaScript be utilized to dynamically adjust the size of all elements on the screen to a specified percentage of their initial height and width when a certain event occurs?

I'm fairly new to the world of JavaScript, but I have a basic understanding of it. I want to optimize my personal website for mobile devices. I've already taken care of screen orientation and element positioning, everything is centered nicely and ...

Navigating through nested arrays in Laravel Blade templates

I have an array that is displaying the code below after being dumped. array:1[ "123"=>array:3[ "test1" => 12345 "test2" => "test" "test3" => 123 ] ] When trying to display each element in an HTML table, the val ...

The server could not locate the URL /about-us that was requested

Upon completing the export process, I am facing an issue on the host where a message is not displaying when I manually enter the link or refresh the page. I have both the server.js and the next module in place. Is there anything else that needs to be done? ...

Add a unique shape to the CSS clip property

Recently, I've been delving into the clip property of CSS and its ability to apply a rectangle or square object. Despite my research efforts, I haven't come across a clear answer to my question. Can you actually use a customized shape with the c ...

Encountered an ERESOLVE error when attempting to install a package, unable to resolve the dependency tree

After attempting to install the necessary dependencies for my project with npm install, an error message came up that I am unable to decipher: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: &l ...

How can I make sure my rows are properly aligned using the Grid

Looking at the image below, I am attempting to align "Ticket Number" and "Email" using a Grid: View My Result Image <Grid container direction="row" justifyContent="flex-start" alignItems="stretch" style={{ pad ...