Joseph A. Joseph A. - 4 months ago 9
HTML Question

CSS - Why are there so many ways to position, and which is the right way?

This is slightly a philosophical and not 100%-hard code-oriented question, but it has to do with programming standards and I hope it fits the rules.

While learning web development, I have always been intrigued by positioning. My first noob websites looked like this:

<body>
<h1> Welcome to my website. </h1>
<br> <br> <br> <br> <br> <br> <br> <br> <br><br> <br> <br>
<p> Copyright 2016 </p>
</body>


However I always felt uneasy doing this - after all, this tag was almost never used in any professional websites I saw, and after asking this question I understood it did not allow for any additional markup and was not semantic.

I looked for other ways, and then stumbled upon
position: absolute
. I basically used this by setting manual position for every element on my page because I did not know any other way to use
position: absolute
and not do it that way. The websites looked fine on my screen but the slightest resize ruined them.

Looking for another solution, I just thought of positioning everything with
margin
. For example, instead of
<br><br>
I would do
margin-top: 5%
. I still do this right now and it feels very wrong.

So I was just looking for general advice -- how does the majority do it? What is best practice? There are apparently hundreds of ways to do it and I've looked through many guides and tutorials but I just don't get CSS positioning.

Answer

The four most commonly used position values are initial, relative, absolute and fixed.

The fixed value is used to position an element at a fixed position on the main screen.

The values absolute and relative are used to put an element in a fixed position relative to a parent. You need to define the element as absolute and his parent as relative.

Then you can do something like this:

<style>
    body{
        position:relative;
    }
    #copyright{
        position:absolute;
        top:5%;
    }
</style>

<body>
    <h1> Welcome to my website. </h1>
    <p id="copyright"> Copyright 2016 </p>
</body>

For more information see w3schools