Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center text in a div and calc() doubts

Tags:

html

css

How can I center the text (p) vertically and horizontally inside a div (.item)?

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <style type="text/css">
        .wrapper {
            width: auto;
            height: 10em;
            background-color: red;
            position: relative;
        }
        .item {
            width: 4em;
            height: 4em;
            background-color: black;
            position: absolute;
            display: inline-block;
            color: white;
        }
        .item p {
            text-align: center;
            vertical-align: middle;
        }
        #top-right {
            right: 0em;
        }
        #center {
            top: calc(50% - 2em);
            right: calc(50% - 2em);
        }
        #bottom-left {
            bottom: 0em;
            left: 0em;
        }
        #bottom-right {
            right: 0em;
            bottom: 0em;
        }
    </style>
</head>
<body>
    <header></header>
    <main>
        <div class="wrapper">
            <div class="item" id="top-left"><p>Top Left</p></div>
            <div class="item" id="top-right"><p>Top Right</p></div>
            <div class="item" id="center"><p>Center</p></div>
            <div class="item" id="bottom-left"><p>Bottom Left</p></div>
            <div class="item" id="bottom-right"><p>Bottom Right</p></div>
        </div>
    </main>
    <footer></footer>
</body>
</html>

It's ok to use calc (because I read that this function isn't supported in some browers)? Or there is another way to center the element #center in the div without calc()?

like image 829
Marco Canora Avatar asked Mar 12 '23 09:03

Marco Canora


2 Answers

In your structure display:table and display:table-cell would not work because you have used position absolute in .item.

Use below css in #center which is supported in all broswers.

#center {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  //top: calc(50% - 2em);
  //right: calc(50% - 2em);
}

example : https://jsfiddle.net/vzk5arxe/2/

like image 102
Gaurav Aggarwal Avatar answered Mar 16 '23 02:03

Gaurav Aggarwal


Another method.

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

Reference: http://colintoh.com/blog/display-table-anti-hero

like image 45
Giri Avatar answered Mar 16 '23 02:03

Giri