Center a DIV horizontally and vertically [duplicate] - html

This question already has answers here:
How to center an element horizontally and vertically
(27 answers)
Closed 7 years ago.
Is there a way to CENTER A DIV vertically and horizontally but, and that is important, that the content will not be cut when the window is smaller than the content The div must have a background color and a width and hight.
I have always centered divs with the absolute positioning and negative margins like in the example provided. But it has the problem that it cuts the content on top. Is there a method to center the div .content without this problem?
I have the example here to play: http://jsbin.com/iquviq/1/edit
CSS:
body { margin: 0px; }
.background {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background-color: yellow;
}
/*
is there a better way than the absolute positioning and negative margin to center the div .content: div with background color a width and a hight?:
*/
.content {
width: 200px;
height: 600px;
background-color: blue;
position:absolute;
top:50%;
left:50%;
margin-left:-100px;/* half width*/
margin-top:-300px;/* half height*/
}
HTML:
<div class="background">
<div class="content"> some text </div>
</div>
My question is not duplicate of "How to center an element horizontally and vertically? " 1- My question was asked before. (just check dates). 2- My question ask very clearly and in black as condition: "the content will not be cut when the window is smaller than the content"

For modern browsers
When you have that luxury. There's flexbox too, but that's not broadly supported at the time of this writing.
HTML:
<div class="content">This works with any content</div>
CSS:
.content {
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
Tinker with it further on Codepen or on JSBin
For older browser support, look elsewhere in this thread.

After trying a lot of things I find a way that works. I share it here if it is useful to anyone. You can see it here working: http://jsbin.com/iquviq/30/edit
.content {
width: 200px;
height: 600px;
background-color: blue;
position: absolute; /*Can also be `fixed`*/
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
/*Solves a problem in which the content is being cut when the div is smaller than its' wrapper:*/
max-width: 100%;
max-height: 100%;
overflow: auto;
}

Here's a demo:
http://www.w3.org/Style/Examples/007/center-example
A method (JSFiddle example)
CSS:
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: table
}
#content {
display: table-cell;
text-align: center;
vertical-align: middle;
}
HTML:
<div id="content">
Content goes here
</div>
Another method
(JSFiddle example)
CSS
body, html, #wrapper {
width: 100%;
height: 100%
}
#wrapper {
display: table
}
#main {
display: table-cell;
vertical-align: middle;
text-align:center
}
HTML
<div id="wrapper">
<div id="main">
Content goes here
</div>
</div>

The legitimate way to do that irrespective of size of the div for any browser size is :
div{
margin:auto;
height: 200px;
width: 200px;
position:fixed;
top:0;
bottom:0;
left:0;
right:0;
background:red;
}
Live Code

You can compare different methods very well explained on this page: http://blog.themeforest.net/tutorials/vertical-centering-with-css/
The method they recommend is adding a empty floating element before the content you cant centered, and clearing it. It doesn't have the downside you mentioned.
I forked your JSBin to apply it : http://jsbin.com/iquviq/7/edit
HTML
<div id="floater">
</div>
<div id="content">
Content here
</div>
CSS
#floater {
float: left;
height: 50%;
margin-bottom: -300px;
}
#content {
clear: both;
width: 200px;
height: 600px;
position: relative;
margin: auto;
}

I do not believe there is a way to do this strictly with CSS. The reason is your "important" qualifier to the question: forcing the parent element to expand with the contents of its child.
My guess is that you will have to use some bits of JavaScript to find the height of the child, and make adjustments.
So, with this HTML:
<div class="parentElement">
<div class="childElement">
...Some Contents...
</div>
</div>
This CSS:
.parentElement {
position:relative;
width:960px;
}
.childElement {
position:absolute;
top:50%;
left:50%;
}
This jQuery might be useful:
$('.childElement').each(function(){
// determine the real dimensions of the element: http://api.jquery.com/outerWidth/
var x = $(this).outerWidth();
var y = $(this).outerHeight();
// adjust parent dimensions to fit child
if($(this).parent().height() < y) {
$(this).parent().css({height: y + 'px'});
}
// offset the child element using negative margins to "center" in both axes
$(this).css({marginTop: 0-(y/2)+'px', marginLeft: 0-(x/2)+'px'});
});
Remember to load the jQ properly, either in the body below the affected elements, or in the head inside of $(document).ready(...).

Related

Why div is being affected from his child?

Empty div like this :
<div class="section" id="s"> </div>
will be at the size of the screen.
But if I put another empty div inside, this section div height will be 0, or it will be in the height of the child's content.
<div class="section" id="s">
<div class="Back"> </div>
</div>
will make this section height to be 0, unless I put something inside Back which will make the section height= openBack's content.
I need to set the section size to be the screen size no matter what happens inside it, and I couldn't.
CSS :
html {
height: 100%;
}
body {
min-height: 100vh;
}
.section {
height: 100%;
width: 100%;
}
.Back {
background-image:url("/images/bg.png");
width: 100%;
height: 100%;
background-size: cover;
justify-content: center;
align-items: center;
}
How can you set the section size to stay screen size constant ?
NOTE: I was answering the original question
You might want to try this:
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
border: 1px solid black;
display: block;
would be able to cover parent div.
Check the following fiddle or snippet:
.hidden{
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
border: 1px solid black;
display: block;
background-color: rgba(254,204,254,0.5);
align-items: center;
flex-direction: column;
}
div.openBack {
position:relative;
border:1px dashed red;
display:flex;
justify-content:center;
align-items:center;
overflow:hidden
}
div.openBack img {
flex-shrink:0;
min-width:100%;
min-height:100%
}
<div class=openBack style="width:100px; height:200px">
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Mona_Lisa_headcrop.jpg/36px-Mona_Lisa_headcrop.jpg">
<div class="hidden"></div>
</div>
Try below css -
.openBack{ position:relative;}
.hidden{
position:absolute;
top:50%;
left:50%;
transform: translate(-50%, -50%);
z-index:9999;
}
To use an image as a background to a section or div, you don't want to include that image as an element. It's pushing the other elements around it out of the way, this is why the next div is pushed below it. And it would be more complicated than necessary to try to get that to behave well by using absolute position.
I would suggest attaching the image as the background-image to either your section's class or id, and remove the <img> element from the html.
either:
.openBack {
background-image: url("/folder/file.png");
}
or
#one {
background-image: url("folder/file.png");
}
You'll want to look up the properties of CSS' background-image to get it to scale and fit the exact way you want.
And you can't use number values at the beginning of IDs.
Hope this helps!
Thanks for all the answers, I found out that the solution was pretty simple (stupid).
The inner div closing tag was wrong <div> instead of </div> which messed up the structure.
Wish I had a tool to find such a mistake.

Adjust size of centered div with fixed div at the left on pure CSS

How to automatically adjust size of the div which is horizontally centred, using another div which has position: fixed property?
To better understand what I mean please take a look at the picture below. Div A is a fixed div with a fixed size and div B is a div which is horizontally centred. I want div B to resize (when I resize browser window) in a such way so right border of A and left border of B never overlap (ideally, if the distance between the borders kept the same).
I know that this can be fairly easy done using JavaScript by reacting on resize events, but I'm wondering is there any way to achieve this in pure CSS?
Here's another way. This should work in older browsers too.
<style>
div {
border: 1px solid red;
height: 100px; }
#A {
position: fixed;
width: 150px; }
#B {
margin: 0px 155px; }
</style>
<div id="A">Stuff</div>
<div id="B">Stuff</div>
How about this:
#a{
width:200px;
}
#b{
width:calc(100% - 400px);
}
Just set the width of B to be 100% of screen width minus twice the width of A and their borders will touch.
When an element is given the settings position: absolute or position: fixed You can change the width of an element by using the left and right properties.
Simply add the same amount to the right as you would to the left
#left {
position: absolute;
width: 150px;
}
#middle {
position: absolute;
left: 165px;
right: 165px;
overflow: auto;
}
/* For demo purposes */
html, body, div { height: 100%; margin: 0; } div { background: red; } #overflow { height: 200%; }
<div id="left"></div>
<div id="middle">
<div id="overflow"></div>
</div>

How to set the height of a div to match the remaining height

I have an HTML page which is divided into 4 sections.
Header
Menu
Content
Footer
I am using 1 div for each section and 1 div which wraps all the 4 divs.
My header's height is 50px, the menu's height is 50px, and the footer's height is 20px.
Then I try setting the menu's height to 100%. Menu div is taking the height of its container which is creating scrollbars in my page.
The CSS is as follows:
html, body {
margin: 0px;
height: 100%;
width: 100%;
min-width: 1024px;
min-height: 500px;
}
#container {
width: 100%;
height: 100%;
}
#header {
width: 100%;
height: 50px;
}
#menu {
width: 100%;
height: 50px;
}
#content {
width: 100%;
height: 100%;
}
#footer {
width: 100%;
height: 20px;
}
Is it possible with CSS alone or I have to use JavaScript also?
Here is another Pure CSS solution, that works without specifying any height whatsoever.
[this solution deserves its own answer]
Here's a Working Fiddle
Why is it good?
because maybe your header will change one day affecting his height, or your menu will grow, or your footer will need an extra line causing his height to grow..
all of that changes will cause you to re-fix another height for the changing element, and recalculate the right height for the content.
my solution makes it easier, because all the parts are fluid.
let them take the space they need in the page, and the content will always take the remaining height.
Browser support:
Tested On: IE10, Firefox, Chrome, Safari, Opera. (not working on older IE, not tested on other browsers)
any Downsides?
yes. unfortunately, because of the way that this trick works, you will need to change the arrangement of your HTML.
I found a Pure CSS way to create a div container, with two child div's.
the first will take the exact height he needs, and the second will take the remaining of the container height's.
but what if I want the opposite scenario,
What if I want second div to take his exact space and the first div to take the container's remaining height?
I didn't find an easy way to do that with Pure CSS.
thats why, I actually reverse the order of the divs, the first holds the second data, and the second holds the first data, now we let the first div to take his exact height, and the second stretch to the end of the container as we want, and then I rotate their view via CSS to make them appear in order.
For your case it means that you will have to create the HTML in that order.
Header
Menu
Footer
Content
The Solution:
HTML:
<div class="Container">
<div class="Header">I'm in the header</div>
<div class="Menu">I'm in the menu</div>
<div class="HeightTaker">
<div class="Wrapper Container Inverse">
<div>
<div class="Footer">I'm in the footer</div>
</div>
<div class="HeightTaker">
<div class="Wrapper">
<div class="Content">
I'm in the content
</div>
</div>
</div>
</div>
</div>
</div>
CSS:
*
{
margin: 0;
padding: 0;
}
html, body, .Container
{
height: 100%;
}
.Container:before
{
content: '';
height: 100%;
float: left;
}
.HeightTaker
{
position: relative;
z-index: 1;
}
.HeightTaker:after
{
content: '';
clear: both;
display: block;
}
.Wrapper
{
position: absolute;
width: 100%;
height: 100%;
}
.Inverse, .Inverse > *
{
-moz-transform: rotateX(180deg);
-ms-transform: rotateX(180deg);
-o-transform: rotate(180deg);
-webkit-transform: rotateX(180deg);
transform: rotateX(180deg);
}
.Header
{
/*for demonstration only*/
background-color: #bf5b5b;
}
.Menu
{
/*for demonstration only*/
background-color: #6ea364;
}
.Content
{
height: 100%;
overflow: auto;
/*for demonstration only*/
background-color: #90adc1;
}
.Footer
{
/*for demonstration only*/
background-color: #b5a8b7;
}
Here's a thought. May not work for your specific problem, but it does address the issue of mixing pixels and percents. Under the current definition of the problem, you use a fixed height for both the top (header, menu) and bottom (footer). But you want to have the content take up the rest. One solution would be to pad the top and bottom of the container with the same height of the header and menu on top and the same height as the footer on the bottom. The problem then is that you have a 100% height container plus 100px on top and 20px on bottom. But there's a CSS convention for that. It's called box-sizing and is very cross browser compatible (as long as you include -moz). in effect, it calculates 100% height after including the padding. Therefore, 100% height plus all the padding still equals 100% height.
In practice it looks like this
HTML
<div class="container">
<div class="header"></div>
<div class="menu"></div>
<div class="content"></div>
<div class="footer"></div>
</div>
CSS
html, body, .container {
min-height: 100%;
background:#eee;
}
.header {
height: 50px;
position: relative;
z-index: 1;
}
.menu {
height: 50px;
position: relative;
z-index: 1;
}
.footer {
height: 20px;
width: 100%; /* needed because this one is position absolute */
bottom: 0%;
position:absolute;
}
.content {
height: 100%;
width: 100%; /* needed because this one is position absolute */
top: 0%;
left: 0%;
padding-top: 100px;
padding-bottom: 20px;
position:absolute;
box-sizing: border-box; /* here's the kicker */
-moz-box-sizing: border-box;
overflow: auto; /* don't panic. they take the place of normal scroll bars*/
}
Demo
http://jsfiddle.net/WLR5S
Source
http://jsfiddle.net/WLR5S/show
http://jsfiddle.net/WLR5S/6/show (with -moz for firefox)
Pros
Obviously, the point is that you can have 100% height elements with padding to compensate for footer and header
Cons
You have to use position absolute for the content and footer, and you have to apply position relative with z-index to the header area
EDIT
After a little more experimenting, I found that it's probably best to use height instead of min-height and apply overflow:auto or the like. That way the page has appropriate sidebars if the content gets to be too large: http://jsfiddle.net/WLR5S/2/ or http://jsfiddle.net/WLR5S/3/
Pure CSS Solution
using calc() (CSS3)
Working Fiddle
HTML:
<div id="container">
<div id="header">header</div>
<div id="menu">menu</div>
<div id="content">content</div>
<div id="footer">footer</div>
</div>
CSS:
html, body {
margin: 0px;
height: 100%;
/*min-width: 1024px;
min-height: 500px;*/ /*You can uncomment that back if you want)*/
}
#container {
height: 100%;
}
#header {
height: 50px;
}
#menu {
height: 50px;
}
#content {
height: calc(100% - 120px); /*120 = 50 + 50 + 20*/
overflow: auto;
}
#footer {
height: 20px;
}
notice I removed your width:100% because this is the default behavior of a block element like a div.
This can also be done without stating any height at all, with Pure CSS.
Check my second answer in that page.

Cannot get my divs to line up side-by-side and fill the page's height

I have the following (jsfiddle):
<div class="content_wrap">
<div class="left_container">
</div>
<div class="right_container">
<div style="background-color: blue; margin:20px; height: 1500px;"></div>
</div>
<div class="clearfix"></div>
</div>
</body>
</html>
CSS:
body,html {
height: 100%;
width: 100%;
background-color: #f8f8f8;
}
div.content_wrap {
width: 100%;
height: 100%;
}
div.left_container {
float:left;
width: 220px;
height: 100%;
background-color: red;
}
div.right_container {
position: relative;
padding: 15px;
padding-top: 100px;
width: 1000px;
}
.clear { clear: both; }
​What I'm trying to do is line the divs side by side and have the left side bar (red) stretch to either the height of the page, or the height taken up by the content (which is in blue), which ever is greater (like the layout shown here)
My problems at the moment are:
The content of the right container (The blue box is just to illustrate content) does not align properly next to the left container
The left container doesn't adjust its height according to the content of the right container.
I've put in a clear fix, although to be quite honest, I don't completely understand how that works.
Would appreciate some guidance.
See this demo: http://jsfiddle.net/PaJ3r/9/
Here is updated CSS for it:
body,html {
height: 100%;
width: 100%;
background-color: #f8f8f8;
}
div.content_wrap {
width: 100%;
position: relative;
}
div.left_container {
float:left;
position:absolute;
width: 220px;
height: 100%;
background-color: red;
}
div.right_container {
position: relative;
padding: 15px;
margin-left: 220px;
padding-top:100px;
width: 1000px;
}
.clear { clear: both; }
position:relative in div.content_wrap is needed in order to get left sidebar stretched to the height of content.
position:absolute; in div.left_container allows left container to fit height of wrapper div.
In div.right_container there is margin-left: 220px; which leave left sidebar visible
Please take a look at this jsfiddle.
So few remarks: I used float: left; on both divs and also, as bart said, you didn't use the correct name for clearfix.
First you should nest your div's so that the left div can grow with the right one.
See updated fiddle
For the left div not set the height, but the min-heigth to 100%. Furthermore you need to play around with margins and paddings to get the last bit ok

Vertically center text in a 100% height div?

I am working with a div that is 100% of the parent divs height.
The div only contains a single line of text.
The div cannot have a fixed height.
So my question is.
How do I vertically center the line of text?
I have tried using:
display: table-cell;
line-height:200%;
If it is important the div is absolutely positioned.
Current CSS
.requests {
position: absolute;
right: 0;
height: 100%;
width: 50px;
padding: 0 10px;
background-color: #69A4B5;
display: table-cell;
vertical-align: middle;
border-bottom-right-radius: 5px;
}
The best and easiest way to do it (currently in 2015 2020) is using flexbox:
.parent-selector {
display: flex;
align-items: center;
}
And that's it :D
Check-out this working example:
div {
border: 1px solid red;
height: 150px;
width: 350px;
justify-content: center;
/* Actual code */
display: flex;
align-items: center;
}
<div>
<p>Hola</p>
</div>
Old answer: You can use vertical-align: middle if you specify also display: table-cell;
.div {
display: table-cell;
vertical-align: middle;
}
Working example:
div {
border: 1px solid red;
height: 150px;
width: 350px;
text-align: center;
/* Actual code */
display: table-cell;
vertical-align: middle;
}
<div>
<p>Hola</p>
</div>
If it does not work you can try setting its parent as display: table;:
.parent-selector {
display: table;
}
Edit: You have this method plus all the methods covered on this question in this other question: How do I vertically center text with CSS?
This answer is no longer the best answer ... see the flexbox answer below instead!
To get it perfectly centered (as mentioned in david's answer) you need to add a negative top margin. If you know (or force) there to only be a single line of text, you can use:
margin-top: -0.5em;
for example:
http://jsfiddle.net/45MHk/623/
//CSS:
html, body, div {
height: 100%;
}
#parent
{
position:relative;
border: 1px solid black;
}
#child
{
position: absolute;
top: 50%;
/* adjust top up half the height of a single line */
margin-top: -0.5em;
/* force content to always be a single line */
overflow: hidden;
white-space: nowrap;
width: 100%;
text-overflow: ellipsis;
}
//HTML:
<div id="parent">
<div id="child">Text that is suppose to be centered</div>
</div>​
The originally accepted answer will not vertically center on the middle of the text (it centers based on the top of the text). So, if you parent is not very tall, it will not look centered at all, for example:
http://jsfiddle.net/45MHk/
//CSS:
#parent
{
position:relative;
height: 3em;
border: 1px solid black;
}
#child
{
position: absolute;
top: 50%;
}​
//HTML:
<div id="parent">
<div id="child">Text that is suppose to be centered</div>
</div>​
Try this one http://jsfiddle.net/Husamuddin/ByNa3/
it works fine with me,
css
.table {
width:100%;
height:100%;
position:absolute;
display:table;
}
.cell {
display:table-cell;
vertical-align:middle;
width:100%;
height:100%:
}
and the html
<div class="table">
<div class="cell">Hello, I'm in the middle</div>
</div>
Since it is absolutely positioned you can use top: 50% to vertically align it in the center.
But then you run into the issue of the page being bigger than you want it to be. For that you can use the overflow: hidden for the parent div. This is what I used to create the same effect:
The CSS:
div.parent {
width: 100%;
height: 300px;
position: relative;
overflow: hidden;
}
div.parent div.absolute {
position: absolute;
top: 50%;
height: 300px;
}
The HTML:
<div class="parent">
<div class="absolute">This is vertically center aligned</div>
</div>
I disagree, here's a JS free solution, which works:
<html style="height: 100%;">
<body style="vertical-align: middle; margin: 0px; height: 100%;">
<div style="height: 100%; width: 100%; display: table; background-color: #ccc;">
<div style="display: table-cell; width: 100%; vertical-align: middle;">
<div style="height: 300px; width: 600px; background-color: wheat; margin-left: auto; margin-right: auto;">A</div>
</div>
</div>
</body>
</html>
Even though this question is pretty old, here's a solution that works with both single and multiple lines that need to be centered vertically (could easily be centered both vertically & horizontally as seen in the css in the Demo.
HTML
<div class="parent">
<div class="child">Text that needs to be vertically centered</div>
</div>
CSS
.parent {
position: relative;
height: 400px;
}
.child {
position: absolute;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
If you know how tall your text is going to be you can use a combination of top:50% and margin-top:-x px where x is half the height of your text.
Working example:
http://jsfiddle.net/Qy4yy/
just wrap your content with a table like this:
<table width="100%" height="100%">
<tr align="center">
<th align="center">
text
</th>
</tr>
</table><
have you tried line-height:1em;? I recall that that's the way to get it to center vertically.
Did you try vertical-align: middle ???
You can find more info on vertical-align here: http://www.w3schools.com/css/pr_pos_vertical-align.asp
Vertical align, dynamic height combined with absolute position is except some special conditions not possible without a few lines of JS (eg. jQuery). (can possibly be solved with backend code in some cases, or min-height combined with sensible top or margin styles, but not perfect)
I mostly only use absolute position when something is supposed to "popup" in relation to something else which is in the float, I think that's the best way to use it so you don't have to fiddle with things like this.
No offense, but most answers in here are way off.
Setting the line height to the same as the height of the div will cause the text to center. Only works if there is one line. (such as a button).
Modern solution - works in all browsers and IE9+
caniuse - browser support.
.v-center {
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
Example: http://jsbin.com/rehovixufe/1/