CSS properties - positioning

revision:


Content

CSS properties - horizontal and vertical alignment CSS properties - center an element JavaScript - positioning methods Javascript - position of the mouse Javascript - click and drag elements CSS properties - "position" property coordinates of an element


CSS properties - horizontal and vertical alignment

top

vertical alignment - "vertical" property

vertical-align: baseline (default):

An cartoon image with a default alignment.

vertical-align: text-top:

An cartoon image with a text-top alignment.

vertical-align: text-bottom:

An cartoon image with a text-bottom alignment.

vertical-align: sub:

An cartoon image with a sub alignment.

vertical-align: sup:

An cartoon image with a super alignment.

code:
                <div class="spec">
                    <h4>vertical-align: baseline (default):</h4>
                    <p>An <img class="a" src=../images/cartoon.jpg" alt="cartoon" width="24" height="24"> 
                    image with a default alignment.</p> 
                    <h4>vertical-align: text-top:</h4>
                    <p>An <img class="b" src="../images/cartoon.jpg" alt="cartoon" width="24" height="24"> 
                    image with a text-top alignment.</p> 
                    <h4>vertical-align: text-bottom:</h4>
                    <p>An <img class="c" src="../images/cartoon.jpg" alt="cartoon" width="24" height="24"> 
                    mage with a text-bottom alignment.</p>
                    <h4>vertical-align: sub:</h4>
                    <p>An <img class="d" src="../images/cartoon.jpg" alt="cartoon" width="24" height="24"> 
                    image with a sub alignment.</p> 
                    <h4>vertical-align: sup:</h4>
                    <p>An <img class="e" src="../images/cartoon.jpg" alt="cartoon" width="24" height="24"> 
                    image with a super alignment.</p>
                </div>
                <style>
                    img.a{vertical-align: baseline;}
                    img.b{vertical-align: text-top;}
                    img.c{vertical-align: text-bottom;}
                    img.d{vertical-align: sub;}
                    img.e{vertical-align: super;}
                </style>
            

CSS properties - horizontal alignment

Hello World!

code:
            <div class="frame">
                <div class="center"><p>Hello World!</p></div>
            </div>
            <style>
                .frame{margin-left: 2vw; width: 40vw; height: 10vw; background-color: skyblue; position: absolute;}
                .center {margin: auto; width: 60%;border: 3px solid #73AD21; padding: 10px;}
            </style>
        

Left aligned

Center aligned

Right aligned

code:
            <div class="frame1">
                <div>
                    <p class='left'>Left aligned</p>
                    <p class='center'>Center aligned</p>
                    <p class='right'>Right aligned</p>
                </div>
                <style>
                    .frame1{width: 40vw; height: 10vw; background-color: skyblue; position: relative;}
                    .frame1 p { border: 1px solid red;}
                    .frame1 .left {text-align: left}
                    .frame1 .center {text-align: center;}
                    .frame1 .right {text-align: right;}
                </style>
            </div>
        
left
right
code:
            <div class="frame1">
                <div>
                    <p class='left'>Left aligned</p>
                    <p class='center'>Center aligned</p>
                    <p class='right'>Right aligned</p>
                </div>
                <style>
                    .frame1{margin-left: 2vw;width: 40vw; height: 10vw; background-color: skyblue; position: relative;}
                    .frame1 p { border: 1px solid red;}
                    .frame1 .left {text-align: left}
                    .frame1 .center {text-align: center;}
                    .frame1 .right {text-align: right;}
                </style>
            </div>
        

CSS properties - center an element

top

align an image center vertically

centered image

The wrapping element needs to be displayed as "table cell" and the vertical-align has to be set to "middle"

code:
                <div class="spec">
                    <p> The wrapping element needs to be displayed as "table cell" and the
                    vertical-align has to be set to "middle"</p>    
                        <div class="verticalcenter">
                            <img src="../images/cartoon.jpg" alt="centered image" width="40%" height="auto"/>
                        </div>
                </div>
                <style>
                    .verticalcenter {display: table-cell; margin: 5vw; border: 0.5vw solid blue; width: 20vw; 
                        height: 20vw; vertical-align: middle; background-color: skyblue;}
                </style>
            

use "transform" or "flex" to center an element

"Positioning" and the "transform" property are used to vertically and horizontally center the div element:

I am vertically and horizontally centered.


Flexbox: a container with both the justify-content and the align-items properties set to center will align the item(s) in the center (in both axis).

I am vertically and horizontally centered.

code:
                <div class="spec">
                    <p class="property">"Positioning" and the "transform" property are used to
                    vertically and horizontally center the div element:</p>
                    <div class="container">
                        <div class="center">
                            <p>I am vertically and horizontally centered.</p>
                        </div>
                    </div>
                    <p class="property">Flexbox: a container with both the justify-content and 
                    the align-items properties set to <em>center</em> will align the item(s) 
                    in the center (in both axis).</p>
                        <div class="center2">
                            <p>I am vertically and horizontally centered.</p>
                        </div>
                </div>
                <style>
                .property{margin-left: 1vw;}
                .container{margin-left: 1vw; height: 10vw; position: relative; border: 0.3vw solid green; 
                    background-color: skyblue;}
                .center{margin: 0; position: absolute; top: 50%; left: 50%; -ms-transform: translate(-50%, -50%); 
                    transform: translate(-50%, -50%);}
                .center2{margin-left: 1vw; display: flex; justify-content: center; align-items: center; 
                    height: 10vw; border: 0.3vw solid green; background-color: skyblue;}
                </style>
            

align a HTML image to the center


in a paragraph

centered image


with margins

margined image

the "center" tag (P.S. obsolete)

center tag
code:
                <div class="spec">
                    <p>in a paragraph</p>  
                        <p class="aligncenter">
                            <img src="../images/cartoon.jpg" alt="centered image" width="10%" height="auto"/>
                        </p><br>
                    <p>with margins</p>
                            <div class="aligncenter">
                                <img class="marginauto" src="../images/cartoon.jpg" alt="margined image" 
                                width="10%" height="auto"/>
                            </div>
                    <p>the "center" tag (P.S. obsolete)</p>
                            <center>
                                <img src="../images/cartoon.jpg" alt="center tag" width="10%" height="auto"/>
                            </center>
                </div>
                <style>
                    .aligncenter {text-align: center; background-color: skyblue;}
                    .marginauto {margin: 1vw auto 2vw;  display: block; }
                    center{background-color: skyblue;}
                </style>
            

both horizontal and vertical centering

centered image
code:
 
                <div class="spec">
                    <div class="verticalhorizontal">
                        <img src="../images/cartoon.jpg" alt="centered image" width="40%" height="auto"/>
                    </div>
                </div>
                <style>
                    .verticalhorizontal {display: table-cell; border: 0.5vw solid blue; height: 20vw; text-align: center; 
                        width: 20vw; vertical-align: middle; background-color: skyblue;}
                </style>
            


JavaScript - positioning methods

top

find the position of an HTML element with "offsetTop"

Click the button



code:
            <div id="target-a">
                <p>Click the button</p>
                <button onclick="getPointA()">Click</button><br><br>
                <p id="output-a"></p>
            </div>
            <script>
                function getPointA() {
                    var target = document.getElementById("target-a");
                    var output = document.getElementById("output-a");
                    output.innerHTML = "offsetTop: " + target.offsetTop;
                }
            </script>
        

find the position of HTML element with "offsetLeft"

Click the button



code:
            <div id="target2">
                <p>Click the button</p>
                <button onclick="getPoint2()">Click</button><br><br>
                <p id="output2"></p>
            </div>
            <script>
                function getPoint2() {
                    var target2 = document.getElementById("target2");
                    var output2 = document.getElementById("output2");
                    output2.innerHTML = "offsetLeft: " + target.offsetLeft;
                }
            </script>
        

get the coordinates of an element

Click the button



code:
            <div id="target3">
                <p>Click the button</p>
                <button onclick="getPoint3()">Click</button><br><br>
                <p id="output3"></p>
            </div>
            <script>
                function getPoint3() {
                    var target3 = document.getElementById("target3");
                    var output3 = document.getElementById("output3");
                    output3.innerHTML = "Coordinate of the element: " +  "(" + target.offsetLeft + ", " +
                    target.offsetTop + ")";
                }
            </script>
        

find the position of HTML element with "getElementById()"

Click the button



code:
            <div id="target">
                <p>Click the button</p>
                <button class="spec" onclick="getPoint()">Click</button><br><br>
                <p id="output"></p>
            </div>
            <script>
                function getPoint() {
                    var target = document.getElementById("target");
                    var output = document.getElementById("output");
                    output.innerHTML = "Co-ordinates of the element (left, top):" + " 
                    (" + target.offsetLeft + ", " + target.offsetTop + ")";
                }
            </script>
        

find the position of HTML element with "getBoundingClientRect()"

code:
            <div>
                <div id="try"></div>  
                <div id="data"></div>
            </div>
            <style>
                #try{width: 20vw;height: 20vw; padding: 20px;  margin: 10px auto; background: skyblue;}
            </style>
            <script>
                let elem = document.querySelector('#try');
                let rect = elem.getBoundingClientRect();
                for (var key in rect) {
                if(typeof rect[key] !== 'function') {
                    let para = document.createElement('p');
                    para.textContent  = `${ key } : ${ rect[key] }`;
                    document.getElementById("data").appendChild(para);
                }
                }
            </script>
        

find the position of HTML element with "getBoundingClientRect()"

Return the top-left corner of this element relative to the top left corner of the viewport with the button below.
Also try to use the scrollbars to test the method for different positions.

code:
            <div class="spec">
                <div style="margin-left: 1vw; height:20vw; width:30vw; overflow:auto;">
                    <div id="myDiv" style="width:25vw; height:15vw; border:1px solid red;">
                    Return the top-left corner of this element relative to the top left corner of the viewport 
                    with the button below.<br>
                    Also try to use the scrollbars to test the method for different positions.
                </div>
                    <div style="width:1000px; height:1000px;"></div>
                </div>
                    <br>
                <button onclick="myFunction()">Get top-left corner + witdth and height of the element
                 with red border</button>
            </div>
            <script>
                function myFunction() {
                var div = document.getElementById("myDiv");
                var rect = div.getBoundingClientRect();
                x = rect.left;
                y = rect.top;
                w = rect.width;
                h = rect.height;
                alert ("Left: " + x + ", Top: " + y + ", Width: " + w + ", Height: " + h);
                }
            </script>
        

find the position of HTML element with "getBoundingClientRect()"

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

code:
            <div class="spec">
                <div style="margin-left: 5vw; height:200px; width:300px; overflow:auto;">
                    <div id="DIV1">
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod 
                        tempor incididunt ut labore et dolore magna aliqua.
                        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi 
                        ut aliquip ex ea commodo consequat.
                    </div>
                </div>
                <button onclick="RectInfo()">get info</button>
                <p id="Sample"></p>
            </div>
            <style>
                #DIV1{width:35vw; height:25vw; border:2px solid blue; color:red;}
            </style>
            <script>
                function RectInfo() {
                    document.getElementById("Sample").innerHTML="";
                    var d = document.getElementById("DIV1");
                    var Rect = d.getBoundingClientRect();
                    rl = Rect.left;
                    rt = Rect.top;
                    rw = Rect.width;
                    rh = Rect.height;
                    document.getElementById("Sample").innerHTML +="Left: " + rl + ",<br> Top: " 
                    + rt + ",<br> Width: " + rw + ",<br> Height: " + rh;
                }
            </script>
        

style the "position" property

change the position of a <div> element from relative to absolute

This div element is placed 2vw from the top of its original position.

Click the button to set the position property to "absolute" and see what happens.

It will then be placed 2vw from the top the page.

code:
            <style>
                #div_1 {border: 1px solid black; background-color: lightblue; width: 30vw; height: 10vw; 
                    position: relative; top: 2vw; margin-bottom: 2vw; }
            </style>
            <button> onclick="position()">change my position</button>
            <script>
                function position() {
                    document.getElementById("div_1").style.position = "absolute";
                }
            </script>
        


JavaScript - position of the mouse

find the position of the mouse relative to the screen

 
code:
            <style>
                #screenBox{margin:1vw; text-align:center; width:40vw; height:25vw; background-color:lightblue;}
                #coordinates{font-size:1.2vw;}   
            </style>
            <div id="screenBox">
                <div id="coordinates"> </div>
            </div>
            <script>
                function findScreenCoords(mouseEvent)
                {
                var xpos;
                var ypos;
                if (mouseEvent)
                {
                    //FireFox
                    xpos = mouseEvent.screenX;
                    ypos = mouseEvent.screenY;
                }
                else
                {
                    //IE
                    xpos = window.event.screenX;
                    ypos = window.event.screenY;
                }
                document.getElementById("screenCoords").innerHTML = xpos + ", " + ypos;
                }
                document.getElementById("screenBox").onmousemove = findScreenCoords;
            </script>
        

find the position of the mouse within an object

 
code:
            <style>
                #objectBox{margin:1vw; text-align:center; width:40vw; height:25vw; background-color:skyblue;}
                #objectCoorcinates{font-size:1.2vw;} 
            </style>
            <div id="objectBox">
                <div id="objectCoordinates"> </div>
            </div>
            <script>
                function findObjectCoords(mouseEvent){
                    var obj = document.getElementById("objectBox");
                    var obj_left = 0;
                    var obj_top = 0;
                    var xpos;
                    var ypos;
                    while (obj.offsetParent){
                        obj_left += obj.offsetLeft;
                        obj_top += obj.offsetTop;
                        obj = obj.offsetParent;
                    }
                    if (mouseEvent){
                        //FireFox
                        xpos = mouseEvent.pageX;
                        ypos = mouseEvent.pageY;
                    }
                    else{
                        //IE
                        xpos = window.event.x + document.body.scrollLeft - 2;
                        ypos = window.event.y + document.body.scrollTop - 2;
                    }
                    xpos -= obj_left;
                    ypos -= obj_top;
                    document.getElementById("objectCoordinates").innerHTML = "xpos: " + xpos + ", ypos: " + ypos;
                }
                document.getElementById("objectBox").onmousemove = findObjectCoords;
            </script>    
        

move an element to the mouse position

move an element with the movement of the mouse

code:
            <style>
                .soccer-field{width: 40vw; height: 20vw; background-color: skyblue;}
                .ball{ width: 2.2vw; height: 2.2vw; border-radius: 50%;  background-color: darkolivegreen; transition: 0.2s;}
            </style>
            <div class="soccer-field">
                <div class="ball"></div>
            </div>
            <script>
                var container = document.querySelector(".soccer-field");
                container.addEventListener('click', function (event) {
                    var x = event.pageX;
                    var y = event.pageY;
                    var ball = document.querySelector(".ball");
                    ball.style.position = "absolute";
                    ball.style.left = `${x}px`;
                    ball.style.top = `${y}px`;
                })
            </script>
        

Javascript - click and drag elements

top

drag a div element

This div can be moved around
code:
            <div class="dragDIV">This div can be moved around</div>
            <style>
                .dragDIV{position: absolute; z-index: 9; text-align: center; border: 1px solid #d3d3d3; 
                    padding: 1vw; cursor: move; background-color: rgb(108, 24, 177); color: #fff; 
                    opacity: 0.4; font-size: 1.2vw; font-weight: 500;}
            </style>
            <script>
                dragElement(document.querySelector(".dragDIV"));
                function dragElement(ele) {
                    var pos1 = 0,
                        pos2 = 0,
                        pos3 = 0,
                        pos4 = 0;
                        if (document.querySelector(ele.id + "header")) {
                            document.getElementById(ele.id + "header").onmousedown = dragMouseDown;
                        }
                        else {
                        ele.onmousedown = dragMouseDown;
                        }
                    function dragMouseDown(e) {
                        e = e || window.event;
                        e.preventDefault();
                        pos3 = e.clientX;
                        pos4 = e.clientY;
                        document.onmouseup = closeDragElement;
                        document.onmousemove = elementDrag;
                    }
                    function elementDrag(e) {
                        e = e || window.event;
                        e.preventDefault();
                        pos1 = pos3 - e.clientX;
                        pos2 = pos4 - e.clientY;
                        pos3 = e.clientX;
                        pos4 = e.clientY;
                        ele.style.top = ele.offsetTop - pos2 + "px";
                        ele.style.left = ele.offsetLeft - pos1 + "px";
                    }
                    function closeDragElement() {
                        document.onmouseup = null;
                        document.onmousemove = null;
                    }
                }
            </script>
        

drag text

drag the text
code:
            <div class="second">
                <a id='text'>drag the text</a>
            </div>    
            <style>
                #text{position: relative; display:flex; z-index: 8; border:0.2vw solid green;
                    justify-content: center; cursor: move; top: 0; width: 8vw; height: 4vw; 
                    background-color:rgb(24, 100, 100);}
            </style>
            <script>
                text.onmousedown = function(event) {
                    let shiftX = event.clientX - text.getBoundingClientRect().left;
                    let shiftY = event.clientY - text.getBoundingClientRect().top;
                    text.style.position = 'absolute';
                    text.style.zIndex = 1000;
                    document.body.append(text);
                    moveAt(event.pageX, event.pageY);
                    function moveAt(pageX, pageY) {
                        text.style.left = pageX - shiftX + 'px';
                        text.style.top = pageY - shiftY + 'px';
                    }
                    function onMouseMove(event) {
                        moveAt(event.pageX, event.pageY);
                    }
                    document.addEventListener('mousemove', onMouseMove);
                    text.onmouseup = function() {
                        document.removeEventListener('mousemove', onMouseMove);
                        text.onmouseup = null;
                    };
                };
                text.ondragstart = function() {
                    return false;
                };
            </script>
        

drag a div element

code:
            <div class=" spec container">
                <div class="drop-targets">
                    <div class="box1">
                        <div class="item" id="item" draggable="true"></div>
                    </div>
                    <div class="box1"></div>
                    <div class="box1"></div>
                </div>
                </div>
                <style>
                .container_one {height: 30vh; width: 30vw; display: flex; flex-direction: column; 
                    justify-content: flex-start; align-items: flex-start;
                    margin: 0vw;}
                .drop-targets {display: flex; flex-direction: row; justify-content: space-around; 
                    align-items: center;margin: 2vw 0; cursor: move;}
                .box1 {height: 8vw; width: 8vw; border: solid 0.3vw green; margin: 1vw; 
                    display: flex; flex-direction: column; align-items: center;
                    justify-content: center;}
                .drag-over {border: dashed 0.3vw red;}
                .item {height: 7.5vw; width: 7.5vw; background-color: #F0DB4F;}
                .hide {display: none;}
                </style>
                <script>
                    /* draggable element */
                    const item = document.querySelector('.item');
                    item.addEventListener('dragstart', dragStart);
                    function dragStart(e) {
                        e.dataTransfer.setData('text/plain', e.target.id);
                        setTimeout(() => {
                            e.target.classList.add('hide');
                        }, 0);
                    }

                    /* drop targets */
                    const boxes = document.querySelectorAll('.box1');
                    boxes.forEach(box => {
                        box.addEventListener('dragenter', dragEnter)
                        box.addEventListener('dragover', dragOver);
                        box.addEventListener('dragleave', dragLeave);
                        box.addEventListener('drop', drop);
                    });

                    function dragEnter(e) {
                        e.preventDefault();
                        e.target.classList.add('drag-over');
                    }
                    function dragOver(e) {
                        e.preventDefault();
                        e.target.classList.add('drag-over');
                    }

                    function dragLeave(e) {
                        e.target.classList.remove('drag-over');
                    }
                    function drop(e) {
                        e.target.classList.remove('drag-over');
                        // get the draggable element
                        const id = e.dataTransfer.getData('text/plain');
                        const draggable = document.getElementById(id);
                        // add it to the drop target
                        e.target.appendChild(draggable);
                        // display the draggable element
                        draggable.classList.remove('hide');
                    }
                </script>
            

drag an image back and forth

cartoon
code:
                <div class="grid-1">
                    <div id="divA" ondrop="drop(event)" ondragover="allowDrop(event)">
                        <img src="cartoon.jpg" width="90%" height="auto" draggable="true" 
                        ondragstart="drag(event)" id="drag1"/>
                    </div>
                    <div id="divB" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
                </div>
                <style>
                    .grid-1{display: flex; flex-flow: row nowrap; justify-content: 
                        start; align-items: start;}
                    #divA, #divB{width: 8vw; height: 8vw; margin: 1vw; padding: 1vw; 
                        border: .1vw solid blue; cursor:pointer;}
                    #divB{transform: rotate(180deg); transition: all 0.5s;}
                </style>
                <script>
                    function allowDrop(ev) {
                    ev.preventDefault();
                    }
                    function drag(ev) {
                    ev.dataTransfer.setData("text", ev.target.id);
                    }
                    function drop(ev) {
                    ev.preventDefault();
                    var data = ev.dataTransfer.getData("text");
                    ev.target.appendChild(document.getElementById(data));
                    }
                </script>
            


CSS properties - "position" property

top

from "relative" to "absolute"

syntax:

1/return the property: object.style.position;
2/set the position property: object.style.position = "static | absolute | fixed | relative | sticky | initial | inherit"

This DIV element is placed 2vw from the top of its original position.

Click the button to set the position property to "absolute" and see what happens.

It will then be placed 2vw from the top of the page.

code:
            <div>
                <button onclick="changePosition()">Try it</button>
            <div id="pos1" class="spec">
            <p>This DIV element is placed 2vw from the top of its original position.</p>
            <p>Click the button to set the position property to "absolute" and see what happens.</p>
            <p>It will then be placed 2vw from the top of the page.</p>
            </div>
            <style>
                #pos1{border: 0.2vw solid black; background-color: yellow; width: 20vw; height: 10vw; 
                    position: relative; top: 2vw; margin-bottom: 3vw;}
            </style>
            <script>
                function changePosition(){
                    document.getElementById("pos1").style.position = "absolute";
                }
            </script>
        

using different position types

I am a div element.
code:
            <div>
                <div id="pos2" style="top:5vw;left:10vw;">I am a div element.</div>
                <select onchange="selectPosition(this);" size="5">
                    <option>absolute
                    <option>fixed
                    <option>static
                    <option>relative
                    <option>sticky
                </select>
            </div>
            <style>
                #pos2{color: red;}
            </style>
            <script>
                function selectPosition(x) {
                    var whichSelected = x.selectedIndex;
                    var posVal = x.options[whichSelected].text;
                    var elem = document.getElementById("pos2");
                    elem.style.position = posVal;
                } 
            </script>
        


coordinates of an element

top

Two coordinates systems:


1/ relative to the window : clientX/clientY;
2/relative to the document : pageX/pageY.


The element.getBoundingClientRect() method returns window coordinates for a minimal rectangle that encloses "element" as an object of built-in "DOMRect" class. Main DOMRect properties: x/y, width/height, top/bottom, left/right.



example to demonstrate how bounding client rect is changing when document is scrolled.

code:
            <div class="spec">
                <div id="example"></div>
                <div id="controls"></div>
            </div>
            <style>
                div#example {width: 20vw; height: 20vw; padding: 1vw; margin: 2vw auto; background: skyblue;}
                p{margin: 0}
            </style>
            <script>
            function update() {
                    const container = document.getElementById("controls");
                    const elem = document.getElementById("example");
                    const rect = elem.getBoundingClientRect();
                    container.innerHTML = "";
                    for (const key in rect) {
                        if (typeof rect[key] !== "function") {
                        let para = document.createElement("p");
                        para.textContent = `${key} : ${rect[key]}`;
                        container.appendChild(para);
                        }
                    }
                }
                
                document.addEventListener("scroll", update);
                update();
            </script>
        


elementFromPoint(x, y)

This method returns the most nested element at window coordinates (x, y).


elementFromPoint(x,y) example

code:
            <div class="spec">
                <p class="ex">elementFromPoint(x,y) example</p>
                <button onclick="showPos()">show</button>
                <div id="pos3"></div>
            </div>
            <script>
                function showPos(){
                    let centerX = document.documentElement.clientWidth /2;
                    let centerY = document.documentElement.clientHeight /2;
                    let elem = document.elementFromPoint(centerX, centerY);
                    elem.style.background = "red";
                    document.getElementById("pos3").innerHTML = elem.tagName;
                };
            </script>