Vertically center div with Javascript (variable height) - javascript

I'm trying to vertically center a div with Javascript. Because the text is going to be changing, I cannot use a fixed height.
I'd like to do this without Jquery.
#box2 {
width: 100%;
height: 100%;
position:relative;
background-color: orange;
}
#informationBox {
padding: 0.5em;
background-color: #fff;
border-radius: 12pt;
border: solid black 3pt;
max-width: 683px;
margin: 0 auto;
text-align: center;
}
Javascript:
var container = document.getElementById("#box2");
var inner = document.getElementById("#informationBox");
var inHeight = inner.offsetHeight;
container.style.height=(window.innerHeight);
container.style.width=window.innerWidth;
var conHeight=container.offsetHeight;
inner.style.marginTop=((conHeight-inHeight)/2);
Any help would be great :)
http://jsfiddle.net/tmyie/EttZQ/

You pretty much have it, you just need to change a couple things. First, getElementById takes just an id-string, not a selector. Secondly, you need to add 'px' to your style declration.
var container = document.getElementById("box2");
var inner = document.getElementById("informationBox");
var inHeight = inner.offsetHeight;
container.style.height = window.innerHeight;
container.style.width = window.innerWidth;
var conHeight = container.offsetHeight;
inner.style.marginTop = ((conHeight-inHeight)/2)+'px';
Here's an updated fiddle: http://jsfiddle.net/EttZQ/1/

Using js with line-height property.
less javascript, and precise centering.
box/info can have min/max-width/height & % or px ...
also resizes with the window.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>center</title>
<style>
html,body{
width:100%;
height:100%;
margin:0;
padding:0;
}
#box{
width:100%;
height:100%;
text-align:center;
}
#info{
display:inline-block;
margin:0;padding:0 16px;
line-height:24px;
border-radius: 12pt;
border: solid black 3pt;
text-align: center;
vertical-align:middle;
box-sizing: border-box;
}
</style>
<script>
var center=function(){
var b=document.getElementById('box');
b.style['line-height']=b.offsetHeight+'px';
}
window.onload=center;
window.onresize=center;
</script>
</head>
<body>
<div id="box"><div id="info">center me pls<br>test</div></div>
</body>
</html>

One simple CSS solution.
http://jsfiddle.net/antouank/EttZQ/2/
body {
margin: 0;
}
#box2 {
width: 100%;
height: 100%;
position:absolute;
background-color: orange;
}
#informationBox {
padding: 0.5em;
background-color: #fff;
border-radius: 12pt;
border: solid black 3pt;
max-width: 100px;
margin: 0 auto;
text-align: center;
position: absolute;
top: 50%;
left: 50%;
}
You only need to calculate the width/height of your element, and change 50% to whatever you need to center it.

Make container pos anything other than static.
Box : pos absolute. top:50%
When box height changes, set margin top of box to -1 * height/2.

Related

Jquery $(window).height() gives wrong value when setting height for document element

So my problem is when i get $(window).height() of an empty document it gives the correct value, but when i set a height for the div (.main-header) the $(window).height() gives it's value plus value close to the div height ,
this picture when i set a height 0 for the .main-header div
and this when i set 700px height for .main-header
i have tried $(window).load() and $(document).ready() and both gave same value https://jsfiddle.net/nev5onff/
$(window).load(function () {
var header = $('.main-header'),
windowH = $(window).height();
$('.test').text( windowH);
});
.main-header {
width: 100%;
height: 700px;
box-shadow: 0 1px 4px #888;
position: relative;
overflow: hidden;
}
.test {
position: fixed;
top: 0;
left: 0;
width: 100px;
float: left;
height: 100px;
background-color: #eee;
color: #000;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="test"></div>
<header class="main-header"></header>
I'm not sure if I understand your question, but I'll try and answer the best I can.
Weave: Pure JS
http://kodeweave.sourceforge.net/editor/#f722c9d64b3e290ec7cc9b4c1a6d19b8
So if you're trying to grab the height of your window/document you can use... (I'm using vanilla/plain js)
var test = document.querySelector('.test');
test.textContent = window.innerHeight;
However if you were grabbing the height of an element, if it has padding that sometimes can add to the elements height depending on how it's styled regardless if it's height is 0 or auto.
In some cases you may want to use clientHeight over innerHeight source
var test = document.querySelector('.test'),
mainHeader = document.querySelector('.main-header');
test.innerHTML = test.clientHeight
Here's a simple fiddle demonstrating this process.
var test = document.querySelector('.test'),
mainHeader = document.querySelector('.main-header');
test.innerHTML = test.clientHeight
.main-header {
width: 100%;
height: 700px;
box-shadow: 0 1px 4px #888;
position: relative;
overflow: hidden;
}
.test {
position: fixed;
top: 0;
left: 0;
width: 100px;
float: left;
height: 100px;
background-color: #eee;
color: #000;
padding: 20px;
}
<div class="test"></div>
<header class="main-header"></header>

Why can't I specify div height in percentage using CSS classes when using jQuery for resizing?

I want to make the div 30% of the height of the window and then on click make it 90%. The thing is I'm only being allowed to specify widths in percentages but with height it breaks unless its px. Any thoughts? Here's a link:
http://codepen.io/chris86/pen/avvWwJ
Here's the html:
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<div id="button" class="banner" value="Switch Class"></div>
Here's the CSS:
.banner {
background-color: #c3c3c3;
height: 100px;
width: 50%;
padding: 0;
margin:0 auto;
}
.bannerbig {
background-color: #000000;
height: 200px;
width: 80%;
padding: 0;
margin:0 auto;
}
And the jQuery:
$(function() {
$('#button').click(function(){
$(".banner").switchClass("banner","bannerbig",'fast');
$(".bannerbig").switchClass("bannerbig","banner",'fast');
return false;
});
});
The reason your code breaks is because using percentage as the value for height or width is dependent on the height of the parent. As far as the DOM is concerned, the only element that has absolute height / width by default is the document object.
So, you have to specify the first DOM elements which don't have absolute height by default as a percentage of the document's height, like so:
html, body {
height: 100%;
}
Then use the appropriate percentage heights for your .banner and .bannerbig classes in CSS:
.banner {
background-color: #c3c3c3;
height: 30%;
width: 50%;
padding: 0;
margin:0 auto;
}
.bannerbig {
background-color: #000000;
height: 90%;
width: 80%;
padding: 0;
margin:0 auto;
}
Hope this helps.

How to attach scroll bar into a div section?

I've just wrote a page with couple div-s and little CSS and javascript.
I don't know how to insert scroll bar into one of my div.
Code is not that hard to understand. CSS and javascript are included in code.
<html>
<head>
<style>
#container
{
vertical-align: top;
width: 98%;
height: 90%;
padding: 5px;
}
#discussion {
width: 99%;
height: 90%;
overflow-y: scroll;
border: 1px solid #ccc;
padding: 5px;
text-align: left;
/*position: absolute; bottom: 0; left: 0;*/
position: relative;
}
#content
{
overflow-y: auto;
position: absolute; bottom: 0; left: 0;
}
#message {
width: 100%;
vertical-align:bottom;
padding: 5px;
border: 1px solid #ccc;
}
</style>
<script>
function init(){
var message = $('#message');
var content = $('#content');
message.keypress(function (e) {
if (e.keyCode == 13 && message.val().length > 0) {
content.append(message.val() + "<br/>");
//content.scrollTop(discussion.get(0).scrollHeight); //works fine with top to down
message.val('').focus();
}
});
};
</script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body onload="javascript:init();">
<div id="container">
<div id="discussion">
<div id="content"></div>
</div>
<input id="message" type="text" placeholder="Hit Enter button to insert"/>
</div>
</body>
</html>
I need scroll bar when content gets out of discussion section.
Thing is when I insert some text with from top to bottom flow scroll bar works fine.
Unfortunately, all text has to be inserted from bottom to top flow.
---------------
-
-
-
-
- first text
---------------
---------------
-
-
-
- first text
- second text
---------------
---------------
- second text
- third text
- fourth text
- fifth text
- sixth text
--------------- now I need a scroll bar to see first text.
You set the height to 90%, but it doesn't know what it's 90% of.
If you want it set to 90% of the body, you'll need to set html,body {height: 100%;}.
Then you need to remove the absolute positioning you put on the content.
Working fiddle here: http://jsfiddle.net/davidpauljunior/2PpqN/
The main cause for the problem is you missed to set the width and height for #content div.
So add it
width: 100%;
height: 100%;
Also for the parent element discussion, instead of using % value stick to static values for height so that user can view it. Currently it is very small to view the scroll.
width: 100%;
height: 200px;
JSFiddle
Hope you understand.
You need to remove overflow from #discussion and change postion to relative in #content
CSS
#discussion {
width: 99%;
height: 90%;
border: 1px solid #ccc;
padding: 5px;
text-align: left;
/*position: absolute; bottom: 0; left: 0;*/
position: relative;
}
#content
{
overflow: auto;
position: relative;
height:100px;
width:100%;
}
updated fiddle

Modify pseudo-element :after's width using javascript [duplicate]

This question already has answers here:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
(26 answers)
Closed 5 years ago.
Markup:
<h1 class="title">Hello World</h1>
CSS:
.title {
border-bottom: 3px solid #aaa;
position: relative;
}
.title:after {
content: "";
width: 100px;
border-bottom: 3px solid red;
display: block;
position: absolute;
}
Demo: http://codepen.io/anon/pen/HDBqe
I wanted to change the .title:after's width based on the text's width, how do I change :after's width using javascript?
$.fn.textWidth = function(){
var html_org = $(this).html();
var html_calc = '<span>' + html_org + '</span>';
$(this).html(html_calc);
var width = $(this).find('span:first').width();
$(this).html(html_org);
return width;
};
$('.title').each(function(){
// Change :after's width based on the text's width
// .css('width', $(this).textWidth());
});
I've found a trick which works in this case. I've updated your demo:
http://codepen.io/anon/pen/bHLtk
.title {
border-bottom: 3px solid #aaa;
position: relative;
min-width: 100%;
}
.title:after {
content: "";
width: inherit;
border-bottom: 3px solid red;
display: block;
position: absolute;
}
Notice, that .title:after has width set to inherit but his parent (.title) has overridden width with min-width. Now I can freely to set width by JavaScript to title and it take effect only on his nested pseudoelement:
$('.title').each(function(){
$(this).css('width', $(this).textWidth());
});
A pseudo-element is not part of the DOM. Therefore, you cannot change its CSS properties directly through JS.
In order to get your desired effect the way you want it, my best guess would be YUI.StyleSheet and manipulate the stylesheet itself, although I have to admit I haven't tested it myself in recent years.
Including such a utility and doing all of this calculation seems like a lot of work for width matching.
If you are willing to compromise a little bit on the semantic HTML, there is a working technique:
Your element takes the entire width of the screen. Wrapping the text with a span and adding the pseudo-element to that, as an inline-block should allow you to get the border under the text only
HTML:
<h1 class="title"><span>Hello World</span></h1>
CSS:
.title {
border-bottom: 3px solid #aaa;
position: relative;
}
.title span{
display:inline-block;
position:relative;
}
.title span:after {
content: "";
width: 100%;
border-bottom: 3px solid red;
display: block;
position: absolute;
}
Here is my version of the codePen.
For future reference:
There is a W3C Candidate Recommendation that suggests the capability of using attributes for CSS properties other than content.
This way, if and when the recommendation is approved and implemented, it might be possible to have the pseudo-element reflect the parent's attributes, as such:
this.setAttribute("length", $(this).textWidth());
And the relevant CSS:
.title:after {
...
width: attr(length px);
...
}
How's this for a different approach.... http://jsfiddle.net/mayYt/
Added CSS
.title span {
border-bottom: 3px solid red;
}
JQuery
$('.title').wrapInner('<span />');
With just a simple trick any pseudo-element can be changed (or at least replaced with something else):
$('.something').click(function(){
$(this).toggleClass('to_show');
});
.something
{
background: red;
height: 40px;
width: 120px;
position: relative;
}
.something.to_show:after
{
content: "X";
color: white;
background: green;
width: 20px;
height: 20px;
position: absolute;
right: 0px;
top: 0px;
display: block;
text-align: center;
}
.something:after
{
content: "O";
color: white;
background: blue;
width: 30px;
height: 25px;
position: absolute;
right: 0px;
top: 0px;
display: block;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div class="something">
click here!
</div>
</body>
</html>

How to get Content Editable div width while writing text inside it?

I am working on a project of HTML and javascript. I have follwing code:-
<html>
<head>
<style type="text/css">
.mainDiv
{
border:1px solid black;
width:500px;
height:340px;
left:400px;
position: absolute;
}
.textOutsideDiv
{
border: 1px dashed black;
position: absolute;
display: none;
width:20px;
height: 20px;
}
.textInsideDiv {
position:absolute;
display:none;
background: none repeat scroll 0 0 transparent;
border: medium none;
font-family: Arial,Helvetica;
line-height: 1em;
margin: 0;
min-height: 1em;
min-width: 1px;
outline: medium none;
padding: 2px;
position: relative;
white-space: nowrap;
z-index: 2;
}
</style>
<script type="text/javascript">
function makeTextCanvas(e)
{
var mouseX=e.pageX-401;
var mouseY=e.pageY-9;
var existOrNot=document.getElementById('textOutsideDiv').style.display;
if(existOrNot=="" || existOrNot=="none")
{
var outerContainer=document.getElementById('textOutsideDiv');
var innerContainer=document.getElementById('textInsideDiv');
outerContainer.style.display='block';
outerContainer.style.left=mouseX+'px';
outerContainer.style.top=mouseY+'px';
innerContainer.style.display='block';
}
}
function makeDiv()
{
//alert("Write Inside");
var outerContainer=document.getElementById('textOutsideDiv');
var innerContainer=document.getElementById('textInsideDiv');
var h=innerContainer.offsetHeight;
outerContainer.style.height=h+'px';
}
</script>
</head>
<body>
<div id="mainDiv" class="mainDiv" onclick="makeTextCanvas(event);">
<div id="textOutsideDiv" class="textOutsideDiv">
<div id="textInsideDiv" class="textInsideDiv" contenteditable="true" onkeyup="makeDiv();" style="font-size: 1em; color: rgb(0, 170, 0);"></div>
</div>
</div>
</body>
</html>
On changing content inside div, i am increasing outerContainer div's height but i am facing a problem in getting width of Content Editable div. How can i solve this problem?
First of all you say that you want to get width of the inner div, but actually you are trying to get innerContainer.offsetHeight. Second, adding text to an element that has its width set to auto does not stretch it if its parent element has fixed width.
If I understood correctly what you were trying to achieve, you want to expand your pseudo-textbox while the user is typing. Here is how you can expand it: http://jsfiddle.net/LwCWM/1/ , but there should be a better way of getting width of the text since non-monospace fonts have letters of various widths.

Categories