CSS flexible layout, flex, media query and implementation of mobile click events

Time:2021-10-15

Flex flexible layout

definition:FlexThe elements of the layout are calledFlexFlex container, referred to as “container”. All its child elements automatically become container members, calledFlexproject

The container has two axes by default: the horizontal spindle(main axis)And vertical cross axis(cross axis )。

The starting position of the spindle (the intersection with the border) is calledmain startThe end position is calledmain end; The starting position of the cross axis is calledcross startThe end position is calledcross end

Items are arranged along the main axis by default. The spindle space occupied by a single project is calledmain sizeThe cross axis space occupied is calledcross size

How to use elastic layout: you only need to set it for the containerdisplay:flex

Container properties


 .box
 { 
flex-direction: row | row-reverse | column | column-reverse;
}

row
row-reverse
column
column-reverse

<style>
    ul:nth-of-type(1){ flex-direction:row;}
    ul:nth-of-type(2){ flex-direction:row-reverse;}
    ul:nth-of-type(3){ flex-direction:column;}
    ul:nth-of-type(4){ flex-direction:column-reverse;}
</style>

 


.box 
{ 
flex-wrap : nowrap| wrap | wrap-reverse ;
}

nowrap
wrap
wrap-reverse

<style>
    ul:nth-of-type(1){flex-wrap:nowrap;}
    ul:nth-of-type(2){flex-wrap:wrap;}
    ul:nth-of-type(3){flex-wrap:wrap-reverse;}
</style>

 


.box 
{
justify-content: flex-start | flex-end | center | space-between | space-around;
}

flex-start
flex-end
center
space-between
space-around

<style>
    ul:nth-of-type(1){justify-content:flex-start;}
    ul:nth-of-type(2){justify-content:flex-end;}
    ul:nth-of-type(3){justify-content:center;}
    ul:nth-of-type(4){justify-content:space-between;}
    ul:nth-of-type(5){justify-content:space-around;}
</style>

.box {  align-items: flex-start | flex-end | center | baseline | stretch;}


flex-start
flex-end
center
baseline
stretch

<style>
    ul:nth-of-type(1){align-items:flex-start;}
    ul:nth-of-type(2){align-items:flex-end;}
    ul:nth-of-type(3){align-items:center;}
    ul:nth-of-type(4){align-items:baseline;}
    ul li{ height:auto;}
    ul:nth-of-type(5){align-items:stretch;}
</style>

align-contentProperty defines the alignment of multiple grid lines. This property has no effect if the project has only one axis.

.box {align-content: flex-start | flex-end | center | space-between | space-around | stretch;}


flex-start
flex-end
center
space-between
space-around
stretch

<style>
    ul:nth-of-type(1){ flex-wrap:wrap; align-content:flex-start;}
    ul:nth-of-type(2){ flex-wrap:wrap; align-content:flex-end;}
    ul:nth-of-type(3){ flex-wrap:wrap; align-content:center;justify-content:center;}
    ul:nth-of-type(4){ flex-wrap:wrap; align-content:space-between;}
    ul:nth-of-type(5){ flex-wrap:wrap; align-content:space-around;}
    ul li{ height:auto;}
    ul:nth-of-type(6){ flex-wrap:wrap;align-content: stretch; justify-content:center;}
</style>

Abbreviation:

flex-flow :

flex-flowProperty isflex-directionProperties andflex-wrapAttribute. The default value isrow nowrap.

box {flex-flow: <flex-direction> || <flex-wrap>;}

Project properties

orderProperty defines the order in which items are arranged. The smaller the value, the higher the arrangement. The default value is0

.item {order: <integer>;}


<style>
    ul li:nth-of-type(3){order:1;}
    ul li:nth-of-type(2){order:2;}
    ul li:nth-of-type(1){order:3;}
    ul li:nth-of-type(5){order:4;}
    ul li:nth-of-type(4){order:5;}
</style>

flex-growProperty defines the magnification of the item. The default is0, that is, if there is space left, it is not enlarged. If all itemsflex-growAll properties are1, they will divide the remaining space equally, if any. If a projectflex-growAttribute is2, other items are1, the former will occupy twice as much space as the other items.

.item { flex-grow: <number>; /* default 0 */}


<style>
    ul li:nth-of-type(1){ flex-grow:1;}
    ul li:nth-of-type(2){ flex-grow:1;}
</style>

flex-shrinkProperty defines the reduction scale of the item. The default is1That is, if there is not enough space, the project will shrink.

If all itemsflex-shrinkAll properties are1, when the space is insufficient, it will be reduced in equal proportion.

If a projectflex-shrinkAttribute is0, other items are1, the former will not shrink when the space is insufficient.

Negative values are not valid for this property.

.item {  flex-shrink: <number>; /* default 1 */}


<style>
    ul li:nth-of-type(1){flex-shrink:0;}
    ul li:nth-of-type(2){flex-shrink:1;}
    ul li:nth-of-type(3){flex-shrink:2;}
    ul li:nth-of-type(4){flex-shrink:3;}
</style>

flex-basisProperty defines the spindle space occupied by the project before allocating excess space(main size)。 Based on this attribute, the browser calculates whether the spindle has excess space. Its default value isauto, that is, the original size of the item. It can be set to the same value as the width or height attribute (for example350px), the project will occupy fixed space.

.item {  flex-basis: <length> | auto; /* default auto */}


<style>
    ul li:nth-of-type(1){ flex-basis:50%;}
</style>

align-selfProperty allows a single item to have a different alignment from other items and can be overwrittenalign-itemsProperties. The default value isautoThat represents the of the inherited parent elementalign-itemsProperty. If there is no parent element, it is equivalent tostretch

.item {  align-self: auto | flex-start | flex-end | center | baseline | stretch;}


<style>
    ul{align-items:flex-start;}
    ul li{height: auto}
    ul li:nth-of-type(1){ align-self:auto;}
    ul li:nth-of-type(2){ align-self:flex-start;}
    ul li:nth-of-type(3){ align-self:center; }
    ul li:nth-of-type(4){ align-self:flex-end;}
    ul li:nth-of-type(5){ align-self:baseline;line-height: 80px;}
    ul li:nth-of-type(6){ align-self:stretch;}
</style>

flexattribute

flexProperty isflex-growflex-shrink  and  flex-basisThe default value is0 1 auto。 The last two properties are optional.

.item { flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]}

This property has two quick values:auto (1 1 auto)andnone (0 0 auto)

It is recommended to use this attribute first rather than write three separate attributes separately, because the browser will calculate the relevant values.

Media query

<!DOCTYPE html>
<html>

<head>
    <title></title>
</head>

<body>
</body>
<script type="text/javascript">
/*
viewport
Definition: a viewport is the area on the screen of the device that can be used to display our web pages. 1px in CSS is not equal to 1px of the device: because the pixel density is different
    Layout viewport: layout viewport
    Generally, browsers of mobile devices set a viewport meta tag by default to define a virtual layout viewport, which is used to solve the problems displayed on mobile phones in early pages
    Visual viewport: visual viewport
    Set the visual area of the physical screen and the physical pixels displayed on the screen. For the same screen, there will be more realistic pixels for devices with high pixel density
    Ideal viewport: ideal viewport
    Get the ideal viewport from the Metab label
    Example: < meta name = "viewport" content = "width = device width, initial scale = 1.0, maximum scale = 1.0" >

*Mobile terminal layout
    *The value of the content attribute of the meta tag
    *Width = device width, height = device height. Make the current viewport width and height equal to the width and height of the device. You can also set a fixed value and try not to use height
    * initial-scale=1.0; Initialize scale: 0.25-1.0
    * maximum-sacle=1.0; Set maximum scale: 0.25-1.0
    * minimum-scale=1.0; Set minimum scale: 0.25-1.0
    * user-scalable=no; Whether to allow users to scale. The default is yes. If it is set to No: then minimax scale and maximum scale will be ignored because scaling is not allowed
    *Example:
    * <meta id="viewport" name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no">

*Mobile terminal gesture event
    *Comparison of event difference with PC
    *MouseMove, mouseup and MouseDown on the PC end will fail or be abnormal on the mobile end
    *The click event on the PC can be used, | not to mention the 300ms problem | but there will be a 300ms delay problem: early mobile phone: used to determine whether it is double-click zoom in and out
    * 
    *Mobile end events
    *Touchstart: triggered by finger pressing
    *Touchmove: triggered when the finger moves
    *Touched: triggered when the finger leaves
    *Touchcancel: the event is triggered when it is interrupted
    * 
    *Mobile end events执行顺序:touchstart->touchmove->touched->click
    * 
    * touchEvent 	   There are three more touchlist attributes compared with the difference between the object and the PC side event
    *Touches a list of all fingers on the current screen
    *Targettouches is a list of fingers on the current DOM object
    *Changedtouhes saves a list of finger objects whose state has changed
    * 
    *There are multiple objects in each touchlist, and the object properties of each touch object
    *The distance of screenx relative to the left side of the screen
    *Screen distance from the top of the screen
    *The distance of clientx relative to the left of the browser
    *Clienty distance from the upper edge of the browser
    *Pagex distance from the left side of the page
    *The distance of pagey relative to the upper edge of the page
    *Current element touched by target
    *Identifier the ID of the currently touched object, which is used to identify the finger
    *Radiusx, radiusy finger touch range
*/
</script>
<style type="text/css">
/*Media query I*/
* {
    margin: 0;
    padding: 0;
}

body {
    background-color: pink;
}

/*You can use @ media query to achieve a responsive layout effect. Different styles will be set according to different conditions*/
/*Screen means the screen, min width: 1200px means the minimum width is 1200px, in other words, what style is it when the screen width is greater than or equal to 1200px*/
@media only screen and (min-width:1200px) {

    /*Write the style here*/
    body {
        background-color: red;
    }
}

/*When the screen width is greater than 800 and less than 1199, the display style*/
@media only screen and (min-width: 800px) and (max-width:1199px) {
    body {
        background-color: aqua;
    }
}

/*When the screen width is greater than 400 and less than 640, the display style*/
/*//If there is no convergence part in the media query, the default part will be displayed*/
@media only screen and (min-width: 400px) and (max-width: 640px) {
    body {
        background-color: yellow;
    }
}
</style>
<!-- 
	Media query II
	<meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=1.0">
	<link rel="stylesheet" href="css/m320.css" media="only screen and (max-width:320px)">
	<link rel="stylesheet" href="css/m375.css" media="only screen and (min-width:321px) and (max-width:375px)">
	<link rel="stylesheet" href="css/m414.css" media="only screen and (min-width:376px) and (max-width:414px)">
 -->

</html>

Mobile terminal click event

<!DOCTYPE html>
<html>

<head>
    <title></title>
</head>

<body>
</body>
<script type="text/javascript">
//Mobile terminal gesture
var box = document.querySelector('#box')
//Click event on PC
box.addEventListener('click', function(e) {
    console.log('===========click============');
    console.log(e);
});
//Finger press
box.addEventListener('touchstart', function(e) {
    console.log('===========touchstart============');
    //            Fn(e);
})
//Finger movement
box.addEventListener('touchmove', function(e) {
    console.log('==========touchmove===========');
    Fn(e);
})
//Finger lift
box.addEventListener('touchend', function() {
    console.log('============touchend==========');
});
//Start after being interrupted
box.addEventListener('touchcancel', function() {
    Alert ('=====================================================================;
})

var touchesH1 = document.querySelector('#box h1:nth-of-type(1)');
var targettouchesH1 = document.querySelector('#box h1:nth-of-type(2)');
var changetouchesH1 = document.querySelector('#box h1:nth-of-type(3)');

function Fn(e) {
    touchesH1.innerHTML = 'touches' + e.touches.length;
    targettouchesH1.innerHTML = 'targettouches' + e.targetTouches.length;
    changetouchesH1.innerHTML = 'changetouches' + e.changedTouches.length;

}

//Using touch Library (mobile terminal)
$('#box').tap(function() {
    console.log('====tap====')
})
$('#box').longTap(function() {
    console.log('====long tap====')
})
$('#box').doubleTap(function() {
    console.log('====double tap====')
})

$('#box').swiperLeft(function() {
    console.log('====left tap====')
})

//Use zepto Library (mobile terminal)
$("#box").tap(function() {
    console.log('======tap=========');
})
$("#box").singleTap(function() {
    console.log('======singleTap=========');
})
$("#box").doubleTap(function() {
    console.log('======doubleTap=========');
})
$("#box").longTap(function() {
    console.log('======longTap=========');
})
$("#box").swipe(function() {
    console.log('======swipeTap=========');
})



//Custom touch event library
//Encapsulate custom touch event library
//Note: the semicolon in front here is to prevent the library from having a semicolon end when referring to other libraries. It is easy to cause problems if the code is compressed in the future
;
(function(window, undefined) {
    var query = function(selector) {
        return query.fn.init(selector);
    };

    query.fn = query.prototype = {
        //Initialization method is to simulate the method of obtaining elements, but what is obtained here is not a real element. The real element is accessed in the element attribute of the whole object
        init: function(selector) {
            if (typeof selector == 'string') {
                this.element = document.querySelector(selector);
                return this;
            }
        },

        //Click. Handler is a callback function, which is the response function made after clicking
        tap: function(handler) {
            this.element.addEventListener('touchstart', touchFn);
            this.element.addEventListener('touchend', touchFn);

            //The time variable used to distinguish and long press is used to make a time difference judgment
            var startTime, endTime;

            function touchFn(e) {
                switch (e.type) {
                    case 'touchstart':
                        //Record a time when pressing
                        startTime = new Date().getTime();
                        break;
                    case 'touchend':
                        //Leave the event to record a time
                        endTime = new Date().getTime();
                        if (endTime - startTime < 500) {
                            //Call back when the gesture leaves
                            handler();
                        }

                        break;

                }
            }
        },
        //Long press
        longTap: function(handler) {
            this.element.addEventListener('touchstart', touchFn);
            this.element.addEventListener('touchend', touchFn);
            //This mobile event is to resolve conflicts with other events
            this.element.addEventListener('touchmove', touchFn);
            var timeId;

            function touchFn(e) {
                switch (e.type) {
                    case 'touchstart':
                        //When the press reaches 500ms, we think it is a long press
                        clearTimeout(timeId);

                        timeId = setTimeout(function() {
                            handler();
                        }, 500);
                        break;
                    case 'touchend':
                        //Clear the timer when you leave
                        clearTimeout(timeId);
                        break;
                    case 'touchmove':
                        //Once moved, the long press timer is cleared
                        clearTimeout(timeId);
                        break;

                }
            }
        },
        //Double click
        doubleTap: function(handler) {
            this.element.addEventListener('touchstart', touchFn);
            this.element.addEventListener('touchend', touchFn);

            //Recording times
            var tapCount = 0,
                timeId;

            function touchFn(e) {
                switch (e.type) {
                    case 'touchstart':
                        //Record once when pressing
                        tapCount++;
                        //When you first come in, clear the timer
                        clearTimeout(timeId);

                        timeId = setTimeout(function() {
                            //If it reaches 500ms, we don't think it's a double-click. We want to reset tapcount
                            tapCount = 0;
                        }, 500);
                        break;
                    case 'touchend':
                        //Clear the timer when you leave
                        if (tapCount == 2) {
                            //Double click only when you press it twice
                            handler();
                            //After double clicking is triggered, the number of clicks is cleared
                            tapCount = 0;
                            //Clear timer
                            clearTimeout(timeId);
                        }

                        break;

                }
            }
        },
        //Left slip
        swiperLeft: function(handler) {
            this.element.addEventListener('touchstart', touchFn);
            this.element.addEventListener('touchend', touchFn);

            //Coordinates of gesture trigger
            var startX, startY, endX, endY;

            function touchFn(e) {
                switch (e.type) {
                    case 'touchstart':
                        //Record the starting coordinates when pressing
                        startX = e.targetTouches[0].pageX;
                        startY = e.targetTouches[0].pageY;
                        break;
                    case 'touchend':
                        //Record the termination coordinates when you leave
                        endX = e.changedTouches[0].pageX;
                        endY = e.changedTouches[0].pageY;
                        //Judge whether it is left-right sliding & & // judge whether it is left sliding or right sliding
                        if (Math.abs(endX - startX) >= Math.abs(endY - startY) && (startX - endX) >= 25) {
                            handler();
                        }
                        break;

                }
            }
        },
    }
    query.fn.init.prototype = query.fn;
    window.$ = window.query = query;
}(window, undefined))
</script>

</html>

This is the end of this article on the implementation of CSS elastic layout flex, media query and mobile click events. For more relevant CSS elastic layout content, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]