Skip to content

Instantly share code, notes, and snippets.

@chbaranowski
Last active February 5, 2018 23:10
Show Gist options
  • Save chbaranowski/3184096e7b7be6f0bbe9c6b14fd767f0 to your computer and use it in GitHub Desktop.
Save chbaranowski/3184096e7b7be6f0bbe9c6b14fd767f0 to your computer and use it in GitHub Desktop.
CSS3 and HTML - Vertical Text Alignment Options
/**
* Atom text center
*/
.text--center {
text-align: center;
width: 100%
}
/**
* Atom box
*/
$box: (
small: (
heigth: 200px,
width: 250px
),
medium: (
heigth: 400px,
width: 300px
)
);
.box {
background: gray;
color: white;
font-size: 24px;
margin: 10px;
}
@each $name, $value in $box {
.box-size--#{$name} {
@extend .box;
height: map-get($value, heigth);
width: map-get($value, width);
}
}
/**
* Box - text vertical alignment center via line height (line-height)
*/
@each $name, $value in $box {
.box-size--#{$name}.box-text--middle {
line-height: map-get($value, heigth);
> * {
display: inline-block;
vertical-align: middle;
line-height: 1em;
}
}
}
/**
* Vertical center all child elements via display table (table and table-cell)
*/
.table--cell-middle {
display: table;
> * {
display: table-cell;
height: 100%;
vertical-align: middle;
}
}
/**
* Vertical center elements and text via display flex (flex layout)
*/
.flex--justify-center {
display:flex;
align-items: center;
justify-content: center;
}
<!DOCTYPE html>
<html>
<body>
<!-- Table cell approach -->
<div class="box box-size--small table--cell-middle text--center">
CENTER <!-- NOT supported !!! -->
</div>
<div class="box box-size--small table--cell-middle">
<span class="text--center">CENTER</span>
</div>
<!-- Flex approach -->
<div class="box box-size--small flex--justify-center">
CENTER
</div>
<div class="box box-size--small flex--justify-center">
<span class="text--center">CENTER</span>
</div>
<!-- Line height approach -->
<div class="box box-size--medium box-text--middle text--center">
CENTER
</div>
<div class="box box-size--medium box-text--middle">
<span class="text--center">CENTER</span>
</div>
</body>
</html>
@chbaranowski
Copy link
Author

@chbaranowski
Copy link
Author

chbaranowski commented Feb 5, 2018

CSS and HTML Example text vertical alignment center (middle): https://jsfiddle.net/3wcp7ezs/6/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment