Fast layout of CSS viewport unit

Time:2021-2-20

**CSS viewport units * * have appeared in the past few years, and as time goes on, more and more developers begin to use them. The advantage of them is that they provide us with a way to dynamically adjust the size without using J avascript. Moreover, if it fails, there are many alternatives.

In this article, we’ll learn about CSS viewport units and how to use them. Let’s start by listing some common problems and their solutions and use cases.

brief introduction

According to the CSS specification, the percentage unit of view is relative to the size of the initial containing block, which is the root element of the web page.

The unit of view is:vwvhvminandvmax

vwThe unit is the percentage of the width of the root element.1vwEqual to the width of the view1%

View width

vwThe unit is the percentage of the width of the root element,1vwEqual to the width of the view1%

Suppose we have an element with the following CSS:


.element {
    width: 50vw;
}

When the width of the view is500pxWhen,50vwThe calculation is as follows


width = 500*50% = 250px

View height

vhThe unit is the percentage of the height of the root element, onevhEqual to the height of the view1%

We have an element with the following CSS:


.element {
    height: 50vh;
}

When the height of the view is290pxWhen,70vhThe calculation is as follows:


height = 290*70% = 202px

Everyone said that there was no project in the resume, so I found a project for you, with a [building tutorial].

Vmin units

vminRepresents the smaller value of the width and height of the viewport, that isvwandvhThe smaller value in. If the width of the viewport is greater than its height, the value is calculated based on the height.

Let’s take the following example.

We have a horizontal screen phone, which has an element withvminUnit. In this case, the value is calculated based on the height of the viewport, because it is less than the width.


.element {
    padding-top: 10vmin;
    padding-bottom: 10vmin;
}

This isvminThe calculation method of this method is as follows:

As you guessed, the results are as follows


padding-top = (10% of height) = 10% * 164 = 16.4px 
 
padding-bottom = (10% of height) = 10% * 164 = 16.4px

Vmax unit

vmaxAndvminInstead, the value isvwandvhThe larger value of.

Let’s take the following example.


.element {
    padding-top: 10vmax;
    padding-bottom: 10vmax;
}

The results are as follows


padding-top = (10% of width) = 10% * 350 = 35px 
padding-bottom = (10% of width) = 10% * 350 = 35p

What’s the difference between units and percentages?

The unit of view is based on the root element of the page, and the percentage is based on the container in which they are located. Therefore, they are different from each other, but each has its own use.

The font size of the use case in the units of the viewport

CSS view units are ideal for responsive typesetting. For example, we can use the following as the title of an article:


.title {
    font-size: 5vw;
}

Titlefont-sizeIncreases or decreases depending on the width of the viewport. Just like the font size provided is the width of the view5%It’s the same. However, if it is used directly without proper testing, it may step into the pit. Let’s watch the following video:

The body size becomes very small, which is not conducive to accessibility and user experience. As far as I know, the minimum font size on a mobile device should not be less than14px. In GIF, not less than10px

To solve this problem, we need to provide a minimum font size for the title, which can be usedcalc()


.title {
    font-size: calc(14px + 2vw);
}

calc()The CSS function will have a minimum value14px, and add on the basis of2vwWith these values, the font size value will not become too small.

Another important issue to consider is the performance of font size on the large screen, such as27” iMac. What’s going to happen? You guessed it. The font size is95pxThat’s a big value. To prevent this, we should use media queries on some breakpoints and change the font size.


@media (min-width: 1800px) {
    .title {
        font-size: 40px;
    }
}

By resetting the font size, we can ensure that the size is not too large. You may also need to add multiple media queries, but it’s up to you, as well as the context of the project.

Case address: https://codepen.io/shadeed/pen/fa989837c6379770cce49f0be6daa3e3

Full screen

Sometimes, we need onepTo get100%For this, we can use theviewportUnit of height.


.p {
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

By addingheight: 100vhWe can make sure thatpHeight will take100%Select the appropriate view. In addition, we added someflexboxTo handle content that is horizontally and vertically centered.

Case source code: https://codepen.io/shadeed/pen/dc4e82f3c873cc64ae5c5bc4a3f4ef9f?editors=1100

Sticky layout (footer)

On the big screen, the content of the website is sometimes very little,footerIt doesn’t stick to the bottom. This is normal and not considered a bad practice. However, there is still room for improvement. Consider the following diagram representing the problem:

In order to solve this problem, we need to give content a height, which is equal toView height – (header + footer). It’s very difficult to do this dynamically, but it’s very easy to use CSS’s view.

The first solution:calcAnd viewport units

IfheaderandfooterIf the height is fixed, you cancalc()The function is combined with the view unit as follows:


header,
footer {
    height: 70px;
}
 
main {
    height: calc(100vh - 70px - 70px);
}

There is no guarantee that this solution will always work, especially forIn footerfor. In my career, I didn’t use fixed height footers because, for example, in different screen sizes, this is not the casefooterIt’s not feasible.

2. The second solution: flexbox and view unit(recommend

Through the100vhSet tobodyThe height of the element, and then you can use flexbox to make itmainThe element takes up the remaining space.


body {
    min-height: 100vh;
    display: flex
    flex-direction: column;
{
 
main {
    /* This will make the main element take the remaining space dynamically */
    flex-grow: 1;
}

In this way, the problem is solved. No matter how long the content is, we have a stickinessfooter

Case source code: https://codepen.io/shadeed/pen/c735b26b8fa97ee685b38084448b3f85?editors=1100

Responsive element

Suppose we have a portfolio to show our responsive design work, and we have three devices (mobile, tablet and laptop). Each device contains an image. The target uses CSS to respond and adapt to these pages.

By using CSS grid and view unit, we can make it completely dynamic and responsive.


<div class="wrapper">
  <div class="device laptop"></div>
  <div class="device mobile"></div>
  <div class="device tablet"></div>
</div>

The viewport units can also be used forgrid- *Property, also used forborderborder-radiusAnd other attributes.


.wrapper {
  display: grid;
  grid-template-columns: repeat(20, 5vw); 
  grid-auto-rows: 6vw;
}
 
.mobile { 
  position: relative;
  z-index: 1;
  grid-column: 2 / span 3;
  grid-row: 3 / span 5;
}
 
.tablet {
  position: relative;
  z-index: 1;
  grid-column: 13 / span 7; 
  grid-row: 4 / span 4;
  border-bottom: 1vw solid #a9B9dd;
  border-right: solid 3vw #a9B9dd;
}
 
.laptop {
  position: relative;
  grid-column: 3/span 13;
  grid-row: 2 / span 8;
}
 
/* Viewport units are used for the bottom, left, right, height, and border-radius. Isn't that cool? */
.laptop:after {
    content:"";
    position:absolute;
    bottom: -3vw;
    left: -5.5vw;
    right: -5.5vw;
    height: 3vw;
    background-color: #a9B9dd;
    border-radius: 0 0 1vw 1vw;
}

Case source code: https://codepen.io/shadeed/pen/2da0f2b70699769f8de3220ff4465bc6?editors=1100

Get out of the container

I noticed that one use case is best for editing a layout. A child element, even if the width of the parent element is limited, occupies the view100%The width of the window. Consider the following:


.break-out {
    width: 100vw;
    position: relative;
    left: 50%;
    right: 50%;
    margin-left: -50vw;
    margin-right: -50vw;
}

Let’s break it down so that we can understand bit by bit how all of these properties work.

1. Addwidth: 100vw

The most important step is to set the width of the image to100%Select the appropriate view.

2. Addmargin-left: -50vw

To center the image, we need to give it a negative margin, half the width of the viewport.

3. Addleft: 50%

Finally, we need to push the image to the right with the value of the parent width50%

Case address: https://codepen.io/shadeed/pen/828f12b1ef7fa7211584ff5c7b82d2fa?editors=1100

Vertical and horizontal spacing

Another interesting use case that comes to mind is to use the units of the view to represent the spacing between elements. This can be related tomargintopbottomandgrid-gapThey are used together. When used, the spacing will be based on the width or height of the viewport, which can be useful for making the layout more dynamic.

Modal box

For modes, we need to push them from the top of the view. In general, usingtopProperty to do this, using a percentage or pixel value. However, for the viewport units, we can add a spacing that can vary according to the height of the viewport.

 


.modal-body {
    top: 20vh;
}

Case address: https://codepen.io/shadeed/pen/f77a0d58947c64c2b3dadbd887700db5?editors=1100

Page header

pageheaderIt’s part of the page introduction. It usually has a title and description, and the height of the upper and lower edges is fixed or filled

For example, there are the following CSS styles:


.page-header {
    padding-top: 10vh;
    padding-bottom: 10vh;
}
 
.page-header h2 {
    margin-bottom: 1.5vh;
}

usevhUnits are used for the padding of the page title and the margin below the title. Notice how the spacing changes!

Case source code: https://codepen.io/shadeed/pen/43024fa031519e316e95bb3ce47f2b22?editors=1100

Vmin and Vmax use cases

The use case is about the top and bottom of the page title elementpadding. When the viewport is small (moving), it is usually reducedpadding. through the use ofvminWe can get the right top and bottom on the basis of the smaller size (width or height) of the viewpadding


.page-header {
    padding: 10vmin 1rem;
}

Case source code: https://codepen.io/shadeed/pen/f335c2f43b960a2c70ea057228ddc5b9?editors=0100

Aspect ratio

We can use itvwUnits creates a response element to maintain its aspect ratio regardless of the size of the viewport.

First, you need to determine the required aspect ratio, and for this example, use9/16


p {
    /* 9/16 * 100 */
    height: 56.25vw;
}

Case source code: https://codepen.io/shadeed/pen/dc4e82f3c873cc64ae5c5bc4a3f4ef9f?editors=0100

Popular top border

Do you know the top border used by most websites? Usually, it’s the same color as the brand, which gives some personality.

We support that the initial value of the border is3px. How do I convert a fixed value to a viewport object? Here is how to calculate its equivalencevw


vw = (Pixel Value / Viewport width) * 100

The width of the viewport is used to estimate the pixel value and the required widthvwThe ratio between units.

For our example, weheaderAdd the following styles:


.header {
    border-top: 4px solid #8f7ebc;  
}

In my case, the width of the viewport is1440(this is not a fixed number, please replace it with your own number)


vw = (4 / 1440) * 100 = 0.277

.header {
    border-top: 0.277vw solid #8f7ebc;  
}

Even better, we can use a base pixel value, while the viewcell can be an additional one.


.header {
    border-top: calc(2px + 0.138vw) solid $color-main;
}

Rolling problem of mobile terminal

There is a common problem in mobile devices, even when using100vh, also scrolls because the address bar is highly visible.Louis HoebregtsWrite an article about this problem, and give a simple solution.

.my-element {
  Height: 100vh; / * rollback of browsers that do not support custom properties*/
  height: calc(var(--vh, 1vh) * 100);
}
//First, we get the height of the view, and we multiply it by 1% to get a value in VH units
let vh = window.innerHeight * 0.01;
//Then, set the value in the '-- VH' custom attribute as an attribute of the root directory of the document
document.documentElement.style.setProperty('--vh', `${vh}px`);

Case source code:https://codepen.io/shadeed/pen/1d18ca2d23ec0038c759dc62dc3fd8c3?editors=0110

This article about CSS viewport unit to achieve fast layout is introduced here. For more relevant CSS viewport unit content, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!