Aligning divs using the baselines of child divs in css - javascript

I can align two div's by simply setting their display to inline-block and using same line-heights like shown in the below:
However, what I want is that aligning two nested divs according to the baseline of the inner divs like this:
I can achieve this also using jquery by taking the longest heading's height and set all the headings' height to this value.
var fitSizes = function () {
var h = 0;
$('h1').each( function(){
if(h < $(this).outerHeight()) h = $(this).outerHeight();
// select biggest height
});
$('h1').each( function(){
$(this).outerHeight(h);
// set all h1 heights to the biggest height
});
};
fitSizes();
But for some reasons I don't want to use js or jquery. Is there any "CSS only" way to achieve something like that?

Any solution I can think of here seems hacky, as are usually problems of this nature. There is ALWAYS a scenario where they will break. A programmatic approach, however bloated and ugly, will definitely give you exactly what you want.
I'm going to make an assumption that both the header and the content are of varying lengths and there may be more than just 2 on page either on a single line or multiple.
TOP DOWN APPROACH // fixed header height
There's no reason why your approach above won't work for a nested div. I would wrap the h1 if you're applying styles to it though. Setting a line-height on a h1 if it breaks across lines will cause each line in the multiline to have that line height. Wrap the header in a div and give that a static height, that way if the has styles such as a background won't be affected by the "margin".
<style>
.wrapper {
height: 2.5rem;
line-height: 2.5rem;
text-align: bottom;
// flex approach works too
}
h1 {
line-height: 1rem;
}
</style>
...
<div class="container">
<div class="wrapper">
<h1>title</h1>
</div>
<div class="content">
<p>lorem ipsum....</p>
</div>
</div>
"BOTTOM UP" APPROACH // fixed content
This would work better if the "anchor" for these components is the bottom of the page. If your content varies in length you could fix the height of the container and content.
<style>
.container {
text-align: bottom;
}
h1 {
line-height: 1rem;
}
.content {
height: 15rem;
overflow: elipsis;
}
</style>
...
<div class="container">
<h1>title</h1>
<div class="content">
<p>lorem ipsum....</p>
</div>
</div>

You could do it with flexbox, you could set make the outer div's siblings by making a container around them and do something like this:
.container {
display: flex;
align-items: flex-end;
}
If this does not fulfill your needs you could also try and see if align-items: baseline; fixes it. Just have a look at flexbox.

What You are looking for using flexbox.
.root {
display: flex;
height: 300px;
border: 2px solid black;
}
.container {
display: flex;
/* position at bottom of container */
margin-top: auto;
/* spread inside container */
flex-grow: 1;
/* align items in row and center it verticaly */
flex-direction: row;
justify-content: center;
}
.column {
display: flex;
margin: auto 5px 5px;
padding: 20px;
/* spread inside container */
flex-grow: 1;
/* align items in column, and position content at the bottom */
flex-direction: column;
justify-content: flex-end;
border: 2px solid blue;
}
.row {
margin: 5px;
padding: 10px;
border: 1px solid red;
text-align: center;
}
<div class="root">
<div class="container">
<div class="column">
<span class="row">row one</span>
</div>
<div class="column">
<span class="row">row one</span>
<span class="row">row two</span>
</div>
</div>
</div>

Flexbox is something up and coming that would be really useful to use. It's only growing in popularity.
This can answer many different problems. Such as your justification issue.
Here's a simple fiddle with little code that shows the answer to your problem: https://jsfiddle.net/hkLk53c6/
HTML:
<div class="container">
<div class="flex-item">
Item
</div>
<div class="flex-item">
Item
<br>
Item
</div>
<div class="flex-item">
Item
<br>
Item
<br>
Item
</div>
</div>
CSS:
.container {
display:flex;
justify-content: space-between;
border: 1px solid #333;
}
.flex-item {
width: 33%;
text-align: center;
background: #120321;
color: #fff;
}
Here's a link to Chris Coyier's explanation about Flexbox Properties:
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
I've personally found it very useful in learning more about flexbox.
You can styled based off of the baseline, you can reverse elements, justify them to be the same height both vertically and horizontally. Etc. It's very exciting because now we can get past some hacky fixes. (Like using JS which trust me, you're not the only one to do so far!)

Related

Centering horizontally a colum of DIV but keeping 'block' for 'display' (CSS style) [duplicate]

How can I horizontally center a <div> within another <div> using CSS?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
With flexbox it is very easy to style the div horizontally and vertically centered.
#inner {
border: 0.05em solid black;
}
#outer {
border: 0.05em solid red;
width:100%;
display: flex;
justify-content: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
To align the div vertically centered, use the property align-items: center.
Other Solutions
You can apply this CSS to the inner <div>:
#inner {
width: 50%;
margin: 0 auto;
}
Of course, you don't have to set the width to 50%. Any width less than the containing <div> will work. The margin: 0 auto is what does the actual centering.
If you are targeting Internet Explorer 8 (and later), it might be better to have this instead:
#inner {
display: table;
margin: 0 auto;
}
It will make the inner element center horizontally and it works without setting a specific width.
Working example here:
#inner {
display: table;
margin: 0 auto;
border: 1px solid black;
}
#outer {
border: 1px solid red;
width:100%
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
If you don't want to set a fixed width on the inner div you could do something like this:
#outer {
width: 100%;
text-align: center;
}
#inner {
display: inline-block;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
That makes the inner div into an inline element that can be centered with text-align.
The best approaches are with CSS3.
The old box model (deprecated)
display: box and its properties box-pack, box-align, box-orient, box-direction etc. have been replaced by flexbox. While they may still work, they are not recommended to be used in production.
#outer {
width: 100%;
/* Firefox */
display: -moz-box;
-moz-box-pack: center;
-moz-box-align: center;
/* Safari and Chrome */
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
/* W3C */
display: box;
box-pack: center;
box-align: center;
}
#inner {
width: 50%;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
According to your usability you may also use the box-orient, box-flex, box-direction properties.
The modern box model with Flexbox
#outer {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
Read more about centering the child elements
CSS Box Model Module Level 3
Box model (CSS2)
box-align on MDN
And this explains why the box model is the best approach:
Why is the W3C box model considered better?
#centered {
position: absolute;
left: 50%;
margin-left: -100px;
}
<div id="outer" style="width:200px">
<div id="centered">Foo foo</div>
</div>
Make sure the parent element is positioned, i.e., relative, fixed, absolute, or sticky.
If you don't know the width of your div, you can use transform:translateX(-50%); instead of the negative margin.
With CSS calc(), the code can get even simpler:
.centered {
width: 200px;
position: absolute;
left: calc(50% - 100px);
}
The principle is still the same; put the item in the middle and compensate for the width.
I've created this example to show how to vertically and horizontally align.
The code is basically this:
#outer {
position: relative;
}
and...
#inner {
margin: auto;
position: absolute;
left:0;
right: 0;
top: 0;
bottom: 0;
}
And it will stay in the center even when you resize your screen.
Some posters have mentioned the CSS 3 way to center using display:box.
This syntax is outdated and shouldn't be used anymore. [See also this post].
So just for completeness here is the latest way to center in CSS 3 using the Flexible Box Layout Module.
So if you have simple markup like:
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
...and you want to center your items within the box, here's what you need on the parent element (.box):
.box {
display: flex;
flex-wrap: wrap; /* Optional. only if you want the items to wrap */
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
.box {
display: flex;
flex-wrap: wrap;
/* Optional. only if you want the items to wrap */
justify-content: center;
/* For horizontal alignment */
align-items: center;
/* For vertical alignment */
}
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
.box {
height: 200px;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
border: 2px solid tomato;
}
.box div {
margin: 0 10px;
width: 100px;
}
.item1 {
height: 50px;
background: pink;
}
.item2 {
background: brown;
height: 100px;
}
.item3 {
height: 150px;
background: orange;
}
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
If you need to support older browsers which use older syntax for flexbox here's a good place to look.
If you don't want to set a fixed width and don't want the extra margin, add display: inline-block to your element.
You can use:
#element {
display: table;
margin: 0 auto;
}
Centering a div of unknown height and width
Horizontally and vertically. It works with reasonably modern browsers (Firefox, Safari/WebKit, Chrome, Internet & Explorer & 10, Opera, etc.)
.content {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<div class="content">This works with any content</div>
Tinker with it further on Codepen or on JSBin.
Set the width and set margin-left and margin-right to auto. That's for horizontal only, though. If you want both ways, you'd just do it both ways. Don't be afraid to experiment; it's not like you'll break anything.
It cannot be centered if you don't give it a width. Otherwise, it will take, by default, the whole horizontal space.
CSS 3's box-align property
#outer {
width: 100%;
height: 100%;
display: box;
box-orient: horizontal;
box-pack: center;
box-align: center;
}
The way I usually do it is using absolute position:
#inner{
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
position: absolute;
}
The outer div doesn't need any extra properties for this to work.
I recently had to center a "hidden" div (i.e., display:none;) that had a tabled form within it that needed to be centered on the page. I wrote the following jQuery code to display the hidden div and then update the CSS content to the automatic generated width of the table and change the margin to center it. (The display toggle is triggered by clicking on a link, but this code wasn't necessary to display.)
NOTE: I'm sharing this code, because Google brought me to this Stack Overflow solution and everything would have worked except that hidden elements don't have any width and can't be resized/centered until after they are displayed.
$(function(){
$('#inner').show().width($('#innerTable').width()).css('margin','0 auto');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inner" style="display:none;">
<form action="">
<table id="innerTable">
<tr><td>Name:</td><td><input type="text"></td></tr>
<tr><td>Email:</td><td><input type="text"></td></tr>
<tr><td>Email:</td><td><input type="submit"></td></tr>
</table>
</form>
</div>
For Firefox and Chrome:
<div style="width:100%;">
<div style="width: 50%; margin: 0px auto;">Text</div>
</div>
For Internet Explorer, Firefox, and Chrome:
<div style="width:100%; text-align:center;">
<div style="width: 50%; margin: 0px auto; text-align:left;">Text</div>
</div>
The text-align: property is optional for modern browsers, but it is necessary in Internet Explorer Quirks Mode for legacy browsers support.
Use:
#outerDiv {
width: 500px;
}
#innerDiv {
width: 200px;
margin: 0 auto;
}
<div id="outerDiv">
<div id="innerDiv">Inner Content</div>
</div>
Another solution for this without having to set a width for one of the elements is using the CSS 3 transform attribute.
#outer {
position: relative;
}
#inner {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
The trick is that translateX(-50%) sets the #inner element 50 percent to the left of its own width. You can use the same trick for vertical alignment.
Here's a Fiddle showing horizontal and vertical alignment.
More information is on Mozilla Developer Network.
Chris Coyier who wrote an excellent post on 'Centering in the Unknown' on his blog. It's a roundup of multiple solutions. I posted one that isn't posted in this question. It has more browser support than the Flexbox solution, and you're not using display: table; which could break other things.
/* This parent can be any width and height */
.outer {
text-align: center;
}
/* The ghost, nudged to maintain perfect centering */
.outer:before {
content: '.';
display: inline-block;
height: 100%;
vertical-align: middle;
width: 0;
overflow: hidden;
}
/* The element to be centered, can
also be of any width and height */
.inner {
display: inline-block;
vertical-align: middle;
width: 300px;
}
I recently found an approach:
#outer {
position: absolute;
left: 50%;
}
#inner {
position: relative;
left: -50%;
}
Both elements must be the same width to function correctly.
For example, see this link and the snippet below:
div#outer {
height: 120px;
background-color: red;
}
div#inner {
width: 50%;
height: 100%;
background-color: green;
margin: 0 auto;
text-align: center; /* For text alignment to center horizontally. */
line-height: 120px; /* For text alignment to center vertically. */
}
<div id="outer" style="width:100%;">
<div id="inner">Foo foo</div>
</div>
If you have a lot of children under a parent, so your CSS content must be like this example on fiddle.
The HTML content look likes this:
<div id="outer" style="width:100%;">
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> Foo Text </div>
</div>
Then see this example on fiddle.
Centering only horizontally
In my experience, the best way to center a box horizontally is to apply the following properties:
The container:
should have text-align: center;
The content box:
should have display: inline-block;
Demo:
.container {
width: 100%;
height: 120px;
background: #CCC;
text-align: center;
}
.centered-content {
display: inline-block;
background: #FFF;
padding: 20px;
border: 1px solid #000;
}
<div class="container">
<div class="centered-content">
Center this!
</div>
</div>
See also this Fiddle!
Centering both horizontally & vertically
In my experience, the best way to center a box both vertically and horizontally is to use an additional container and apply the following properties:
The outer container:
should have display: table;
The inner container:
should have display: table-cell;
should have vertical-align: middle;
should have text-align: center;
The content box:
should have display: inline-block;
Demo:
.outer-container {
display: table;
width: 100%;
height: 120px;
background: #CCC;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
background: #FFF;
padding: 20px;
border: 1px solid #000;
}
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
Center this!
</div>
</div>
</div>
See also this Fiddle!
Flexbox
display: flex behaves like a block element and lays out its content according to the flexbox model. It works with justify-content: center.
Please note: Flexbox is compatible all browsers exept Internet Explorer. See display: flex not working on Internet Explorer for a complete and up to date list of browsers compatibility.
#inner {
display: inline-block;
}
#outer {
display: flex;
justify-content: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Text-align: center
Applying text-align: center the inline contents are centered within the line box. However since the inner div has by default width: 100% you have to set a specific width or use one of the following:
display: block
display: inline
display: inline-block
#inner {
display: inline-block;
}
#outer {
text-align: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Margin: 0 auto
Using margin: 0 auto is another option and it is more suitable for older browsers compatibility. It works together with display: table.
#inner {
display: table;
margin: 0 auto;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Transform
transform: translate lets you modify the coordinate space of the CSS visual formatting model. Using it, elements can be translated, rotated, scaled, and skewed. To center horizontally it require position: absolute and left: 50%.
#inner {
position: absolute;
left: 50%;
transform: translate(-50%, 0%);
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
<center> (Deprecated)
The tag <center> is the HTML alternative to text-align: center. It works on older browsers and most of the new ones but it is not considered a good practice since this feature is obsolete and has been removed from the Web standards.
#inner {
display: inline-block;
}
<div id="outer">
<center>
<div id="inner">Foo foo</div>
</center>
</div>
This method also works just fine:
div.container {
display: flex;
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
For the inner <div>, the only condition is that its height and width must not be larger than the ones of its container.
The easiest way:
#outer {
width: 100%;
text-align: center;
}
#inner {
margin: auto;
width: 200px;
}
<div id="outer">
<div id="inner">Blabla</div>
</div>
Flex have more than 97% browser support coverage and might be the best way to solve these kind of problems within few lines:
#outer {
display: flex;
justify-content: center;
}
If width of the content is unknown you can use the following method. Suppose we have these two elements:
.outer -- full width
.inner -- no width set (but a max-width could be specified)
Suppose the computed width of the elements are 1000 pixels and 300 pixels respectively. Proceed as follows:
Wrap .inner inside .center-helper
Make .center-helper an inline block; it becomes the same size as .inner making it 300 pixels wide.
Push .center-helper 50% right relative to its parent; this places its left at 500 pixels wrt. outer.
Push .inner 50% left relative to its parent; this places its left at -150 pixels wrt. center helper which means its left is at 500 - 150 = 350 pixels wrt. outer.
Set overflow on .outer to hidden to prevent horizontal scrollbar.
Demo:
body {
font: medium sans-serif;
}
.outer {
overflow: hidden;
background-color: papayawhip;
}
.center-helper {
display: inline-block;
position: relative;
left: 50%;
background-color: burlywood;
}
.inner {
display: inline-block;
position: relative;
left: -50%;
background-color: wheat;
}
<div class="outer">
<div class="center-helper">
<div class="inner">
<h1>A div with no defined width</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br>
Duis condimentum sem non turpis consectetur blandit.<br>
Donec dictum risus id orci ornare tempor.<br>
Proin pharetra augue a lorem elementum molestie.<br>
Nunc nec justo sit amet nisi tempor viverra sit amet a ipsum.</p>
</div>
</div>
</div>
You can do something like this
#container {
display: table;
width: <width of your container>;
height: <height of your container>;
}
#inner {
width: <width of your center div>;
display: table-cell;
margin: 0 auto;
text-align: center;
vertical-align: middle;
}
This will also align the #inner vertically. If you don't want to, remove the display and vertical-align properties;
Here is what you want in the shortest way.
JSFIDDLE
#outer {
margin - top: 100 px;
height: 500 px; /* you can set whatever you want */
border: 1 px solid# ccc;
}
#inner {
border: 1 px solid# f00;
position: relative;
top: 50 % ;
transform: translateY(-50 % );
}
You can use display: flex for your outer div and to horizontally center you have to add justify-content: center
#outer{
display: flex;
justify-content: center;
}
or you can visit w3schools - CSS flex Property for more ideas.
Well, I managed to find a solution that maybe will fit all situations, but uses JavaScript:
Here's the structure:
<div class="container">
<div class="content">Your content goes here!</div>
<div class="content">Your content goes here!</div>
<div class="content">Your content goes here!</div>
</div>
And here's the JavaScript snippet:
$(document).ready(function() {
$('.container .content').each( function() {
container = $(this).closest('.container');
content = $(this);
containerHeight = container.height();
contentHeight = content.height();
margin = (containerHeight - contentHeight) / 2;
content.css('margin-top', margin);
})
});
If you want to use it in a responsive approach, you can add the following:
$(window).resize(function() {
$('.container .content').each( function() {
container = $(this).closest('.container');
content = $(this);
containerHeight = container.height();
contentHeight = content.height();
margin = (containerHeight - contentHeight) / 2;
content.css('margin-top', margin);
})
});
One option existed that I found:
Everybody says to use:
margin: auto 0;
But there is another option. Set this property for the parent div. It
works perfectly anytime:
text-align: center;
And see, child go center.
And finally CSS for you:
#outer{
text-align: center;
display: block; /* Or inline-block - base on your need */
}
#inner
{
position: relative;
margin: 0 auto; /* It is good to be */
}

Position DIV relative to it's Parent Parent [duplicate]

How can I horizontally center a <div> within another <div> using CSS?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
With flexbox it is very easy to style the div horizontally and vertically centered.
#inner {
border: 0.05em solid black;
}
#outer {
border: 0.05em solid red;
width:100%;
display: flex;
justify-content: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
To align the div vertically centered, use the property align-items: center.
Other Solutions
You can apply this CSS to the inner <div>:
#inner {
width: 50%;
margin: 0 auto;
}
Of course, you don't have to set the width to 50%. Any width less than the containing <div> will work. The margin: 0 auto is what does the actual centering.
If you are targeting Internet Explorer 8 (and later), it might be better to have this instead:
#inner {
display: table;
margin: 0 auto;
}
It will make the inner element center horizontally and it works without setting a specific width.
Working example here:
#inner {
display: table;
margin: 0 auto;
border: 1px solid black;
}
#outer {
border: 1px solid red;
width:100%
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
If you don't want to set a fixed width on the inner div you could do something like this:
#outer {
width: 100%;
text-align: center;
}
#inner {
display: inline-block;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
That makes the inner div into an inline element that can be centered with text-align.
The best approaches are with CSS3.
The old box model (deprecated)
display: box and its properties box-pack, box-align, box-orient, box-direction etc. have been replaced by flexbox. While they may still work, they are not recommended to be used in production.
#outer {
width: 100%;
/* Firefox */
display: -moz-box;
-moz-box-pack: center;
-moz-box-align: center;
/* Safari and Chrome */
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
/* W3C */
display: box;
box-pack: center;
box-align: center;
}
#inner {
width: 50%;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
According to your usability you may also use the box-orient, box-flex, box-direction properties.
The modern box model with Flexbox
#outer {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
Read more about centering the child elements
CSS Box Model Module Level 3
Box model (CSS2)
box-align on MDN
And this explains why the box model is the best approach:
Why is the W3C box model considered better?
#centered {
position: absolute;
left: 50%;
margin-left: -100px;
}
<div id="outer" style="width:200px">
<div id="centered">Foo foo</div>
</div>
Make sure the parent element is positioned, i.e., relative, fixed, absolute, or sticky.
If you don't know the width of your div, you can use transform:translateX(-50%); instead of the negative margin.
With CSS calc(), the code can get even simpler:
.centered {
width: 200px;
position: absolute;
left: calc(50% - 100px);
}
The principle is still the same; put the item in the middle and compensate for the width.
I've created this example to show how to vertically and horizontally align.
The code is basically this:
#outer {
position: relative;
}
and...
#inner {
margin: auto;
position: absolute;
left:0;
right: 0;
top: 0;
bottom: 0;
}
And it will stay in the center even when you resize your screen.
Some posters have mentioned the CSS 3 way to center using display:box.
This syntax is outdated and shouldn't be used anymore. [See also this post].
So just for completeness here is the latest way to center in CSS 3 using the Flexible Box Layout Module.
So if you have simple markup like:
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
...and you want to center your items within the box, here's what you need on the parent element (.box):
.box {
display: flex;
flex-wrap: wrap; /* Optional. only if you want the items to wrap */
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
.box {
display: flex;
flex-wrap: wrap;
/* Optional. only if you want the items to wrap */
justify-content: center;
/* For horizontal alignment */
align-items: center;
/* For vertical alignment */
}
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
.box {
height: 200px;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
border: 2px solid tomato;
}
.box div {
margin: 0 10px;
width: 100px;
}
.item1 {
height: 50px;
background: pink;
}
.item2 {
background: brown;
height: 100px;
}
.item3 {
height: 150px;
background: orange;
}
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
If you need to support older browsers which use older syntax for flexbox here's a good place to look.
If you don't want to set a fixed width and don't want the extra margin, add display: inline-block to your element.
You can use:
#element {
display: table;
margin: 0 auto;
}
Centering a div of unknown height and width
Horizontally and vertically. It works with reasonably modern browsers (Firefox, Safari/WebKit, Chrome, Internet & Explorer & 10, Opera, etc.)
.content {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<div class="content">This works with any content</div>
Tinker with it further on Codepen or on JSBin.
Set the width and set margin-left and margin-right to auto. That's for horizontal only, though. If you want both ways, you'd just do it both ways. Don't be afraid to experiment; it's not like you'll break anything.
It cannot be centered if you don't give it a width. Otherwise, it will take, by default, the whole horizontal space.
CSS 3's box-align property
#outer {
width: 100%;
height: 100%;
display: box;
box-orient: horizontal;
box-pack: center;
box-align: center;
}
The way I usually do it is using absolute position:
#inner{
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
position: absolute;
}
The outer div doesn't need any extra properties for this to work.
I recently had to center a "hidden" div (i.e., display:none;) that had a tabled form within it that needed to be centered on the page. I wrote the following jQuery code to display the hidden div and then update the CSS content to the automatic generated width of the table and change the margin to center it. (The display toggle is triggered by clicking on a link, but this code wasn't necessary to display.)
NOTE: I'm sharing this code, because Google brought me to this Stack Overflow solution and everything would have worked except that hidden elements don't have any width and can't be resized/centered until after they are displayed.
$(function(){
$('#inner').show().width($('#innerTable').width()).css('margin','0 auto');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inner" style="display:none;">
<form action="">
<table id="innerTable">
<tr><td>Name:</td><td><input type="text"></td></tr>
<tr><td>Email:</td><td><input type="text"></td></tr>
<tr><td>Email:</td><td><input type="submit"></td></tr>
</table>
</form>
</div>
For Firefox and Chrome:
<div style="width:100%;">
<div style="width: 50%; margin: 0px auto;">Text</div>
</div>
For Internet Explorer, Firefox, and Chrome:
<div style="width:100%; text-align:center;">
<div style="width: 50%; margin: 0px auto; text-align:left;">Text</div>
</div>
The text-align: property is optional for modern browsers, but it is necessary in Internet Explorer Quirks Mode for legacy browsers support.
Use:
#outerDiv {
width: 500px;
}
#innerDiv {
width: 200px;
margin: 0 auto;
}
<div id="outerDiv">
<div id="innerDiv">Inner Content</div>
</div>
Another solution for this without having to set a width for one of the elements is using the CSS 3 transform attribute.
#outer {
position: relative;
}
#inner {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
The trick is that translateX(-50%) sets the #inner element 50 percent to the left of its own width. You can use the same trick for vertical alignment.
Here's a Fiddle showing horizontal and vertical alignment.
More information is on Mozilla Developer Network.
Chris Coyier who wrote an excellent post on 'Centering in the Unknown' on his blog. It's a roundup of multiple solutions. I posted one that isn't posted in this question. It has more browser support than the Flexbox solution, and you're not using display: table; which could break other things.
/* This parent can be any width and height */
.outer {
text-align: center;
}
/* The ghost, nudged to maintain perfect centering */
.outer:before {
content: '.';
display: inline-block;
height: 100%;
vertical-align: middle;
width: 0;
overflow: hidden;
}
/* The element to be centered, can
also be of any width and height */
.inner {
display: inline-block;
vertical-align: middle;
width: 300px;
}
I recently found an approach:
#outer {
position: absolute;
left: 50%;
}
#inner {
position: relative;
left: -50%;
}
Both elements must be the same width to function correctly.
For example, see this link and the snippet below:
div#outer {
height: 120px;
background-color: red;
}
div#inner {
width: 50%;
height: 100%;
background-color: green;
margin: 0 auto;
text-align: center; /* For text alignment to center horizontally. */
line-height: 120px; /* For text alignment to center vertically. */
}
<div id="outer" style="width:100%;">
<div id="inner">Foo foo</div>
</div>
If you have a lot of children under a parent, so your CSS content must be like this example on fiddle.
The HTML content look likes this:
<div id="outer" style="width:100%;">
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> Foo Text </div>
</div>
Then see this example on fiddle.
Centering only horizontally
In my experience, the best way to center a box horizontally is to apply the following properties:
The container:
should have text-align: center;
The content box:
should have display: inline-block;
Demo:
.container {
width: 100%;
height: 120px;
background: #CCC;
text-align: center;
}
.centered-content {
display: inline-block;
background: #FFF;
padding: 20px;
border: 1px solid #000;
}
<div class="container">
<div class="centered-content">
Center this!
</div>
</div>
See also this Fiddle!
Centering both horizontally & vertically
In my experience, the best way to center a box both vertically and horizontally is to use an additional container and apply the following properties:
The outer container:
should have display: table;
The inner container:
should have display: table-cell;
should have vertical-align: middle;
should have text-align: center;
The content box:
should have display: inline-block;
Demo:
.outer-container {
display: table;
width: 100%;
height: 120px;
background: #CCC;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
background: #FFF;
padding: 20px;
border: 1px solid #000;
}
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
Center this!
</div>
</div>
</div>
See also this Fiddle!
Flexbox
display: flex behaves like a block element and lays out its content according to the flexbox model. It works with justify-content: center.
Please note: Flexbox is compatible all browsers exept Internet Explorer. See display: flex not working on Internet Explorer for a complete and up to date list of browsers compatibility.
#inner {
display: inline-block;
}
#outer {
display: flex;
justify-content: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Text-align: center
Applying text-align: center the inline contents are centered within the line box. However since the inner div has by default width: 100% you have to set a specific width or use one of the following:
display: block
display: inline
display: inline-block
#inner {
display: inline-block;
}
#outer {
text-align: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Margin: 0 auto
Using margin: 0 auto is another option and it is more suitable for older browsers compatibility. It works together with display: table.
#inner {
display: table;
margin: 0 auto;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Transform
transform: translate lets you modify the coordinate space of the CSS visual formatting model. Using it, elements can be translated, rotated, scaled, and skewed. To center horizontally it require position: absolute and left: 50%.
#inner {
position: absolute;
left: 50%;
transform: translate(-50%, 0%);
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
<center> (Deprecated)
The tag <center> is the HTML alternative to text-align: center. It works on older browsers and most of the new ones but it is not considered a good practice since this feature is obsolete and has been removed from the Web standards.
#inner {
display: inline-block;
}
<div id="outer">
<center>
<div id="inner">Foo foo</div>
</center>
</div>
This method also works just fine:
div.container {
display: flex;
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
For the inner <div>, the only condition is that its height and width must not be larger than the ones of its container.
The easiest way:
#outer {
width: 100%;
text-align: center;
}
#inner {
margin: auto;
width: 200px;
}
<div id="outer">
<div id="inner">Blabla</div>
</div>
Flex have more than 97% browser support coverage and might be the best way to solve these kind of problems within few lines:
#outer {
display: flex;
justify-content: center;
}
If width of the content is unknown you can use the following method. Suppose we have these two elements:
.outer -- full width
.inner -- no width set (but a max-width could be specified)
Suppose the computed width of the elements are 1000 pixels and 300 pixels respectively. Proceed as follows:
Wrap .inner inside .center-helper
Make .center-helper an inline block; it becomes the same size as .inner making it 300 pixels wide.
Push .center-helper 50% right relative to its parent; this places its left at 500 pixels wrt. outer.
Push .inner 50% left relative to its parent; this places its left at -150 pixels wrt. center helper which means its left is at 500 - 150 = 350 pixels wrt. outer.
Set overflow on .outer to hidden to prevent horizontal scrollbar.
Demo:
body {
font: medium sans-serif;
}
.outer {
overflow: hidden;
background-color: papayawhip;
}
.center-helper {
display: inline-block;
position: relative;
left: 50%;
background-color: burlywood;
}
.inner {
display: inline-block;
position: relative;
left: -50%;
background-color: wheat;
}
<div class="outer">
<div class="center-helper">
<div class="inner">
<h1>A div with no defined width</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br>
Duis condimentum sem non turpis consectetur blandit.<br>
Donec dictum risus id orci ornare tempor.<br>
Proin pharetra augue a lorem elementum molestie.<br>
Nunc nec justo sit amet nisi tempor viverra sit amet a ipsum.</p>
</div>
</div>
</div>
You can do something like this
#container {
display: table;
width: <width of your container>;
height: <height of your container>;
}
#inner {
width: <width of your center div>;
display: table-cell;
margin: 0 auto;
text-align: center;
vertical-align: middle;
}
This will also align the #inner vertically. If you don't want to, remove the display and vertical-align properties;
Here is what you want in the shortest way.
JSFIDDLE
#outer {
margin - top: 100 px;
height: 500 px; /* you can set whatever you want */
border: 1 px solid# ccc;
}
#inner {
border: 1 px solid# f00;
position: relative;
top: 50 % ;
transform: translateY(-50 % );
}
You can use display: flex for your outer div and to horizontally center you have to add justify-content: center
#outer{
display: flex;
justify-content: center;
}
or you can visit w3schools - CSS flex Property for more ideas.
Well, I managed to find a solution that maybe will fit all situations, but uses JavaScript:
Here's the structure:
<div class="container">
<div class="content">Your content goes here!</div>
<div class="content">Your content goes here!</div>
<div class="content">Your content goes here!</div>
</div>
And here's the JavaScript snippet:
$(document).ready(function() {
$('.container .content').each( function() {
container = $(this).closest('.container');
content = $(this);
containerHeight = container.height();
contentHeight = content.height();
margin = (containerHeight - contentHeight) / 2;
content.css('margin-top', margin);
})
});
If you want to use it in a responsive approach, you can add the following:
$(window).resize(function() {
$('.container .content').each( function() {
container = $(this).closest('.container');
content = $(this);
containerHeight = container.height();
contentHeight = content.height();
margin = (containerHeight - contentHeight) / 2;
content.css('margin-top', margin);
})
});
One option existed that I found:
Everybody says to use:
margin: auto 0;
But there is another option. Set this property for the parent div. It
works perfectly anytime:
text-align: center;
And see, child go center.
And finally CSS for you:
#outer{
text-align: center;
display: block; /* Or inline-block - base on your need */
}
#inner
{
position: relative;
margin: 0 auto; /* It is good to be */
}

I have an element centered in the screen and I want another element to be centered just right below the first element [duplicate]

How can I horizontally center a <div> within another <div> using CSS?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
With flexbox it is very easy to style the div horizontally and vertically centered.
#inner {
border: 0.05em solid black;
}
#outer {
border: 0.05em solid red;
width:100%;
display: flex;
justify-content: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
To align the div vertically centered, use the property align-items: center.
Other Solutions
You can apply this CSS to the inner <div>:
#inner {
width: 50%;
margin: 0 auto;
}
Of course, you don't have to set the width to 50%. Any width less than the containing <div> will work. The margin: 0 auto is what does the actual centering.
If you are targeting Internet Explorer 8 (and later), it might be better to have this instead:
#inner {
display: table;
margin: 0 auto;
}
It will make the inner element center horizontally and it works without setting a specific width.
Working example here:
#inner {
display: table;
margin: 0 auto;
border: 1px solid black;
}
#outer {
border: 1px solid red;
width:100%
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
If you don't want to set a fixed width on the inner div you could do something like this:
#outer {
width: 100%;
text-align: center;
}
#inner {
display: inline-block;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
That makes the inner div into an inline element that can be centered with text-align.
The best approaches are with CSS3.
The old box model (deprecated)
display: box and its properties box-pack, box-align, box-orient, box-direction etc. have been replaced by flexbox. While they may still work, they are not recommended to be used in production.
#outer {
width: 100%;
/* Firefox */
display: -moz-box;
-moz-box-pack: center;
-moz-box-align: center;
/* Safari and Chrome */
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
/* W3C */
display: box;
box-pack: center;
box-align: center;
}
#inner {
width: 50%;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
According to your usability you may also use the box-orient, box-flex, box-direction properties.
The modern box model with Flexbox
#outer {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
Read more about centering the child elements
CSS Box Model Module Level 3
Box model (CSS2)
box-align on MDN
And this explains why the box model is the best approach:
Why is the W3C box model considered better?
#centered {
position: absolute;
left: 50%;
margin-left: -100px;
}
<div id="outer" style="width:200px">
<div id="centered">Foo foo</div>
</div>
Make sure the parent element is positioned, i.e., relative, fixed, absolute, or sticky.
If you don't know the width of your div, you can use transform:translateX(-50%); instead of the negative margin.
With CSS calc(), the code can get even simpler:
.centered {
width: 200px;
position: absolute;
left: calc(50% - 100px);
}
The principle is still the same; put the item in the middle and compensate for the width.
I've created this example to show how to vertically and horizontally align.
The code is basically this:
#outer {
position: relative;
}
and...
#inner {
margin: auto;
position: absolute;
left:0;
right: 0;
top: 0;
bottom: 0;
}
And it will stay in the center even when you resize your screen.
Some posters have mentioned the CSS 3 way to center using display:box.
This syntax is outdated and shouldn't be used anymore. [See also this post].
So just for completeness here is the latest way to center in CSS 3 using the Flexible Box Layout Module.
So if you have simple markup like:
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
...and you want to center your items within the box, here's what you need on the parent element (.box):
.box {
display: flex;
flex-wrap: wrap; /* Optional. only if you want the items to wrap */
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
.box {
display: flex;
flex-wrap: wrap;
/* Optional. only if you want the items to wrap */
justify-content: center;
/* For horizontal alignment */
align-items: center;
/* For vertical alignment */
}
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
.box {
height: 200px;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
border: 2px solid tomato;
}
.box div {
margin: 0 10px;
width: 100px;
}
.item1 {
height: 50px;
background: pink;
}
.item2 {
background: brown;
height: 100px;
}
.item3 {
height: 150px;
background: orange;
}
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
If you need to support older browsers which use older syntax for flexbox here's a good place to look.
If you don't want to set a fixed width and don't want the extra margin, add display: inline-block to your element.
You can use:
#element {
display: table;
margin: 0 auto;
}
Centering a div of unknown height and width
Horizontally and vertically. It works with reasonably modern browsers (Firefox, Safari/WebKit, Chrome, Internet & Explorer & 10, Opera, etc.)
.content {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<div class="content">This works with any content</div>
Tinker with it further on Codepen or on JSBin.
Set the width and set margin-left and margin-right to auto. That's for horizontal only, though. If you want both ways, you'd just do it both ways. Don't be afraid to experiment; it's not like you'll break anything.
It cannot be centered if you don't give it a width. Otherwise, it will take, by default, the whole horizontal space.
CSS 3's box-align property
#outer {
width: 100%;
height: 100%;
display: box;
box-orient: horizontal;
box-pack: center;
box-align: center;
}
The way I usually do it is using absolute position:
#inner{
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
position: absolute;
}
The outer div doesn't need any extra properties for this to work.
I recently had to center a "hidden" div (i.e., display:none;) that had a tabled form within it that needed to be centered on the page. I wrote the following jQuery code to display the hidden div and then update the CSS content to the automatic generated width of the table and change the margin to center it. (The display toggle is triggered by clicking on a link, but this code wasn't necessary to display.)
NOTE: I'm sharing this code, because Google brought me to this Stack Overflow solution and everything would have worked except that hidden elements don't have any width and can't be resized/centered until after they are displayed.
$(function(){
$('#inner').show().width($('#innerTable').width()).css('margin','0 auto');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inner" style="display:none;">
<form action="">
<table id="innerTable">
<tr><td>Name:</td><td><input type="text"></td></tr>
<tr><td>Email:</td><td><input type="text"></td></tr>
<tr><td>Email:</td><td><input type="submit"></td></tr>
</table>
</form>
</div>
For Firefox and Chrome:
<div style="width:100%;">
<div style="width: 50%; margin: 0px auto;">Text</div>
</div>
For Internet Explorer, Firefox, and Chrome:
<div style="width:100%; text-align:center;">
<div style="width: 50%; margin: 0px auto; text-align:left;">Text</div>
</div>
The text-align: property is optional for modern browsers, but it is necessary in Internet Explorer Quirks Mode for legacy browsers support.
Use:
#outerDiv {
width: 500px;
}
#innerDiv {
width: 200px;
margin: 0 auto;
}
<div id="outerDiv">
<div id="innerDiv">Inner Content</div>
</div>
Another solution for this without having to set a width for one of the elements is using the CSS 3 transform attribute.
#outer {
position: relative;
}
#inner {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
The trick is that translateX(-50%) sets the #inner element 50 percent to the left of its own width. You can use the same trick for vertical alignment.
Here's a Fiddle showing horizontal and vertical alignment.
More information is on Mozilla Developer Network.
Chris Coyier who wrote an excellent post on 'Centering in the Unknown' on his blog. It's a roundup of multiple solutions. I posted one that isn't posted in this question. It has more browser support than the Flexbox solution, and you're not using display: table; which could break other things.
/* This parent can be any width and height */
.outer {
text-align: center;
}
/* The ghost, nudged to maintain perfect centering */
.outer:before {
content: '.';
display: inline-block;
height: 100%;
vertical-align: middle;
width: 0;
overflow: hidden;
}
/* The element to be centered, can
also be of any width and height */
.inner {
display: inline-block;
vertical-align: middle;
width: 300px;
}
I recently found an approach:
#outer {
position: absolute;
left: 50%;
}
#inner {
position: relative;
left: -50%;
}
Both elements must be the same width to function correctly.
For example, see this link and the snippet below:
div#outer {
height: 120px;
background-color: red;
}
div#inner {
width: 50%;
height: 100%;
background-color: green;
margin: 0 auto;
text-align: center; /* For text alignment to center horizontally. */
line-height: 120px; /* For text alignment to center vertically. */
}
<div id="outer" style="width:100%;">
<div id="inner">Foo foo</div>
</div>
If you have a lot of children under a parent, so your CSS content must be like this example on fiddle.
The HTML content look likes this:
<div id="outer" style="width:100%;">
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> Foo Text </div>
</div>
Then see this example on fiddle.
Centering only horizontally
In my experience, the best way to center a box horizontally is to apply the following properties:
The container:
should have text-align: center;
The content box:
should have display: inline-block;
Demo:
.container {
width: 100%;
height: 120px;
background: #CCC;
text-align: center;
}
.centered-content {
display: inline-block;
background: #FFF;
padding: 20px;
border: 1px solid #000;
}
<div class="container">
<div class="centered-content">
Center this!
</div>
</div>
See also this Fiddle!
Centering both horizontally & vertically
In my experience, the best way to center a box both vertically and horizontally is to use an additional container and apply the following properties:
The outer container:
should have display: table;
The inner container:
should have display: table-cell;
should have vertical-align: middle;
should have text-align: center;
The content box:
should have display: inline-block;
Demo:
.outer-container {
display: table;
width: 100%;
height: 120px;
background: #CCC;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
background: #FFF;
padding: 20px;
border: 1px solid #000;
}
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
Center this!
</div>
</div>
</div>
See also this Fiddle!
Flexbox
display: flex behaves like a block element and lays out its content according to the flexbox model. It works with justify-content: center.
Please note: Flexbox is compatible all browsers exept Internet Explorer. See display: flex not working on Internet Explorer for a complete and up to date list of browsers compatibility.
#inner {
display: inline-block;
}
#outer {
display: flex;
justify-content: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Text-align: center
Applying text-align: center the inline contents are centered within the line box. However since the inner div has by default width: 100% you have to set a specific width or use one of the following:
display: block
display: inline
display: inline-block
#inner {
display: inline-block;
}
#outer {
text-align: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Margin: 0 auto
Using margin: 0 auto is another option and it is more suitable for older browsers compatibility. It works together with display: table.
#inner {
display: table;
margin: 0 auto;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Transform
transform: translate lets you modify the coordinate space of the CSS visual formatting model. Using it, elements can be translated, rotated, scaled, and skewed. To center horizontally it require position: absolute and left: 50%.
#inner {
position: absolute;
left: 50%;
transform: translate(-50%, 0%);
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
<center> (Deprecated)
The tag <center> is the HTML alternative to text-align: center. It works on older browsers and most of the new ones but it is not considered a good practice since this feature is obsolete and has been removed from the Web standards.
#inner {
display: inline-block;
}
<div id="outer">
<center>
<div id="inner">Foo foo</div>
</center>
</div>
This method also works just fine:
div.container {
display: flex;
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
For the inner <div>, the only condition is that its height and width must not be larger than the ones of its container.
The easiest way:
#outer {
width: 100%;
text-align: center;
}
#inner {
margin: auto;
width: 200px;
}
<div id="outer">
<div id="inner">Blabla</div>
</div>
Flex have more than 97% browser support coverage and might be the best way to solve these kind of problems within few lines:
#outer {
display: flex;
justify-content: center;
}
If width of the content is unknown you can use the following method. Suppose we have these two elements:
.outer -- full width
.inner -- no width set (but a max-width could be specified)
Suppose the computed width of the elements are 1000 pixels and 300 pixels respectively. Proceed as follows:
Wrap .inner inside .center-helper
Make .center-helper an inline block; it becomes the same size as .inner making it 300 pixels wide.
Push .center-helper 50% right relative to its parent; this places its left at 500 pixels wrt. outer.
Push .inner 50% left relative to its parent; this places its left at -150 pixels wrt. center helper which means its left is at 500 - 150 = 350 pixels wrt. outer.
Set overflow on .outer to hidden to prevent horizontal scrollbar.
Demo:
body {
font: medium sans-serif;
}
.outer {
overflow: hidden;
background-color: papayawhip;
}
.center-helper {
display: inline-block;
position: relative;
left: 50%;
background-color: burlywood;
}
.inner {
display: inline-block;
position: relative;
left: -50%;
background-color: wheat;
}
<div class="outer">
<div class="center-helper">
<div class="inner">
<h1>A div with no defined width</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br>
Duis condimentum sem non turpis consectetur blandit.<br>
Donec dictum risus id orci ornare tempor.<br>
Proin pharetra augue a lorem elementum molestie.<br>
Nunc nec justo sit amet nisi tempor viverra sit amet a ipsum.</p>
</div>
</div>
</div>
You can do something like this
#container {
display: table;
width: <width of your container>;
height: <height of your container>;
}
#inner {
width: <width of your center div>;
display: table-cell;
margin: 0 auto;
text-align: center;
vertical-align: middle;
}
This will also align the #inner vertically. If you don't want to, remove the display and vertical-align properties;
Here is what you want in the shortest way.
JSFIDDLE
#outer {
margin - top: 100 px;
height: 500 px; /* you can set whatever you want */
border: 1 px solid# ccc;
}
#inner {
border: 1 px solid# f00;
position: relative;
top: 50 % ;
transform: translateY(-50 % );
}
You can use display: flex for your outer div and to horizontally center you have to add justify-content: center
#outer{
display: flex;
justify-content: center;
}
or you can visit w3schools - CSS flex Property for more ideas.
Well, I managed to find a solution that maybe will fit all situations, but uses JavaScript:
Here's the structure:
<div class="container">
<div class="content">Your content goes here!</div>
<div class="content">Your content goes here!</div>
<div class="content">Your content goes here!</div>
</div>
And here's the JavaScript snippet:
$(document).ready(function() {
$('.container .content').each( function() {
container = $(this).closest('.container');
content = $(this);
containerHeight = container.height();
contentHeight = content.height();
margin = (containerHeight - contentHeight) / 2;
content.css('margin-top', margin);
})
});
If you want to use it in a responsive approach, you can add the following:
$(window).resize(function() {
$('.container .content').each( function() {
container = $(this).closest('.container');
content = $(this);
containerHeight = container.height();
contentHeight = content.height();
margin = (containerHeight - contentHeight) / 2;
content.css('margin-top', margin);
})
});
One option existed that I found:
Everybody says to use:
margin: auto 0;
But there is another option. Set this property for the parent div. It
works perfectly anytime:
text-align: center;
And see, child go center.
And finally CSS for you:
#outer{
text-align: center;
display: block; /* Or inline-block - base on your need */
}
#inner
{
position: relative;
margin: 0 auto; /* It is good to be */
}

How to insert content into an background image? [duplicate]

I'm trying to get a H1 vertically center aligned within a div that has a background image.
I tried this method I found: https://jsfiddle.net/vdqdpyc0/12/
But found that the full height of the banner was only visible if I specifically added a px height to the div, or added padding to either element. This meant that when I resized, there was lots of white space above and below the banner. This wouldn't be an issue if the background was intended to repeat, but it isn't.
The end product needs to look like this.
html,
body {
height: 100%;
}
.outer-wrapper {
background: url("http://paulmason.name/media/demos/full-screen-background-image/background.jpg") no-repeat center center;
background-size: cover;
max-height: 360px;
height: 100%;
}
.inner-wrapper {
display: table;
width: 100%;
height: 100%;
}
.header-wrapper {
display: table-cell;
text-align: center;
vertical-align: middle;
}
h1 {
color: #fff;
}
<div class="outer-wrapper">
<div class="inner-wrapper">
<div class="header-wrapper">
<h1>
Vertically aligned text
</h1>
</div>
</div>
</div>
I could go through reducing the padding for various responsive viewpoints, but I figured there has to be a more streamlined way of going about it.
You can achieve this much more easily these days with flexbox, e.g.
html,
body {
height: 100%;
}
.outer-wrapper {
background: url("http://paulmason.name/media/demos/full-screen-background-image/background.jpg") no-repeat center center;
background-size: cover;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
h1 {
color: #fff;
}
<div class="outer-wrapper">
<div class="inner-wrapper">
<div class="header-wrapper">
<h1>
Vertically aligned text
</h1>
</div>
</div>
</div>
Example: https://jsfiddle.net/0yxctLne/
You can use a flexbox for this. Here is a pretty simple guide to flexbox. For your issue, it should be enough to pass
display: flex;
flex-direction: column;
justify-content: center;
to the element surrounding the H1 tag, IF the surrounding element is the same height and width as the space you want the H1 tag to be centered in. This will define the main axis as vertical (read: column) and then center all content along the main axis. If you want, you can also add
align-items: center;
to have the text centered along the cross axis (as in horizontally).
Do you need something like this? Flexbox is a nice way to do:
.header-wrapper {
background: url("http://paulmason.name/media/demos/full-screen-background-image/background.jpg") no-repeat center center;
background-size: cover;
text-align: center;
display: flex;
align-items: center;
justify-content: center;
}
h1 {
color: #fff;
}
<div class="outer-wrapper">
<div class="inner-wrapper">
<div class="header-wrapper">
<h1>
Vertically aligned text
</h1>
</div>
</div>
</div>
Fiddle

How to left-align centered text only if hits a line break?

How can I condition my text to become left-aligned if hits the end of its contained space and has to switch to the next line? Is there something inherent within CSS that can detect it, or does it have to be a JavaScript solution?
Here's the fiddle so you can see how it should behave: https://jsfiddle.net/fj4ddmey/2/
.text.container {
margin: 0 auto;
text-align: center;
width: 350px;
border: 1px solid black;
}
.text.container.two {
text-align: left;
}
<div class="text container">
<p>This is how short sentences should look</p>
</div>
<div class="text container">
<p>This text should be left aligned because it hits a line break</p>
</div>
<div class="text container two">
<p>This is how it should look, but it needs to be a fluid solution</p>
</div>
Use flexbox like that
.container {
display: flex;
justify-content: center;
}
<div class="container">
<p>This is how it should look, but it needs to be a fluid solution</p>
</div>
Here is JSFiddle demo
You can set the <p> as inline block, so that text-align:center on the container will center the <p> tag first, rather than the text. And inline-block has the shrink-to-fit feature, means the width is determined by the content, and never goes beyond the container, with text-align:left, text inside will be left aligned when it wraps.
.container {
width: 350px;
margin: 0 auto;
text-align: center;
outline: 1px solid black;
}
.container p {
display: inline-block;
text-align: left;
outline: 1px dotted red;
}
<div class="container">
<p>This is how short sentences should look</p>
</div>
<div class="container">
<p>This text should be left aligned because it hits a line break</p>
</div>
You can use jQuery to determine the element height, and if its greater than one line, add a class to justify the text appropriately.
Something like this should work:
function countLines(e) {
var elementHeight = e.innerHeight();
var lineHeight = parseInt(e.css('line-height'));
var lines = elementHeight / lineHeight;
return(lines > 1);
}
$('p').each(function() {
if(countLines($(this))) {
$(this).addClass('two'); //class to left justify
}
})
You can see it working here: https://jsfiddle.net/igor_9000/fj4ddmey/1/

Categories