#CSS Tricks ##Center an element in a parent element
Last active
August 29, 2015 14:02
-
-
Save dewwwald/ed665aab9fd23ac97dda to your computer and use it in GitHub Desktop.
CSS Tips and Tricks case study's. Center an element in another block element.
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
//some-page.html | |
<div class="container"> | |
<div class="element"> | |
</div> | |
</div> |
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
//style.css | |
//Parent element | |
.container { | |
height: 300px; /* The height must be known in order for this to work */ | |
text-align: center; /* align the inline(-block) elements horizontally */ | |
font: 0/0 a; /* remove the gap between inline(-block) elements */ | |
} | |
.container:before { /* create a full-height inline block pseudo=element */ | |
content: ' '; | |
display: inline-block; | |
vertical-align: middle; /* vertical alignment of the inline element */ | |
height: 100%; | |
} | |
.element { | |
display: inline-block; | |
vertical-align: middle; /* vertical alignment of the inline element */ | |
font: 16px/1 Arial sans-serif; /* <-- reset the font property */ | |
} | |
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
//style.css | |
//Parent element | |
.parent { | |
position: relative; | |
} | |
//child | |
.element { | |
position: absolute; | |
top: 50%; | |
left: 50%; | |
/* Here you can use a mixin to prefix if your using sass for transform */ | |
transform: translate(-50%, -50%); | |
/* for ie8 this wont work */ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment