Last active
June 22, 2019 18:33
-
-
Save trszdev/27ba6fe1f737bc6d9a0a350588bf5772 to your computer and use it in GitHub Desktop.
CSS - Center inline-block element both vertically and horizontally (https://jsfiddle.net/r9hn4a0L/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Centering text</title> | |
<style> | |
.outer { | |
width: 300px; | |
height: 300px; | |
margin-bottom: 10px; | |
} | |
.solution-1 { | |
background: yellow; | |
display: flex; | |
justify-content: center; | |
align-items: center; | |
} | |
.solution-2 { | |
background: pink; | |
position: relative; | |
} | |
.solution-2 > span { | |
position: absolute; | |
left: 50%; | |
top: 50%; | |
transform: translate(-50%, -50%); | |
} | |
.solution-3 { | |
background: lightgreen; | |
display: table-cell; | |
vertical-align: middle; | |
text-align: center; | |
} | |
.solution-4 { | |
background: aqua; | |
line-height: 300px; | |
vertical-align: middle; | |
text-align: center; | |
/* since margin isn't applied to table-cell */ | |
position: relative; | |
top: 10px; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="outer solution-1"><span>text to be centered #1</span></div> | |
<div class="outer solution-2"><span>text to be centered #2</span></div> | |
<div class="outer solution-3"><span>text to be centered #3</span></div> | |
<div class="outer solution-4"><span>text to be centered #4</span></div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment