Child Element Moves Baseline - javascript

I have a dropdown widget that can be used inline, but when it opens it seems to lower the text baseline. I would have expected the children of the widget not to affect layout.
With some experimentation, I found that it matters whether or not there is text in the div, so there are two widgets in the following example.
var divs = document.querySelectorAll('div div');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', function() {
this.classList.toggle('high')
});
}
div {
background-color: #ddf;
width: 150px;
height: 20px;
overflow: visible;
display: inline-block;
}
.third {
display: block;
}
.high {
height: 100px;
}
<div>
<div></div>
</div>
<div>
<div>Text</div>
</div>
<div>
<div class="third"></div>
</div>Text
It seems like the inner div is treated like text if there is not actual text. Is there a way to eliminate this behavior?
I can only change the divs and not what follows, so I'd be interested in a solution that allows me to make the parent div solely determine the baseline.
EDIT: Not making the child display: inline-block also seems to work. This seems to confirm that the contents are being treated as the "text" that matters. I'd still like to know why.

does this solve your problem. I added only float: left to the <div> 's. Here's Fiddle <http://jsfiddle.net/zlajaa1/ffebcww0/>

Related

Inconsistent behavior of inline-block elements when created via JavaScript

I have a bunch of the same divs whose display property is set to inline-block. I know that inline-block elements have, by default, some margin around them so without any modification, I would expect some free space surrounding these elements (this question is not about removing them).
If I simply hard-code them into html file, then they behave as I expect them to.
* {
margin: 0;
padding: 0;
}
div.box {
width: 100px;
height: 40px;
background: red;
display: inline-block;
}
<div tabindex="1" class='box'></div>
<div class='box'></div>
<div class='box'></div>
But if I start adding them via JavaScript, the top and bottom margins stays the same, but left and right seems to disappear.
In this code, if I tab into the first element and then hit enter, the new div is created and added into DOM but as mentioned above, margins are gone when I start adding more of them (hitting enter multiple times).
const btn = document.querySelector('div.box');
btn.addEventListener('keypress', event => {
if (event.key === 'Enter') {
const box = document.createElement('div');
box.className = 'box';
document.body.appendChild(box);
}
});
* {
margin: 0;
padding: 0;
}
div.box {
width: 100px;
height: 40px;
background: red;
display: inline-block;
}
<div tabindex="1" class='box'></div>
Anyone knows why there is a difference in how these divs are rendered when hard-coded vs added programmatically? Is there something wrong with the JavaScript code?
You're confusing white space with margins. Inline elements are sensitive to white space in your code, so when you generate them via JS, that whitespace doesn't exist unless you manually add it. The easiest way to see this is in your first example by putting all your divs on the same line with no spaces or carriage returns.
* {
margin: 0;
padding: 0;
}
div.box {
width: 100px;
height: 40px;
background: red;
display: inline-block;
}
<div tabindex="1" class='box'></div><div class='box'></div><div class='box'></div>

Make popup have smart positioning

I am working on a piece of legacy code for a table. In certain cells, I'm adding a notice icon. When you hover over the icon a <span> is made visible displaying some information. I would like to be able to make this <span> smart about its positioning but can't figure out a good method. I can statically position it but depending on which cell in the table it is in it gets lost against the edge of the page. I have done a JsFiddle here demonstrating the issue. Unfortunately, I am not allowed to use anything but HTML, CSS and vanilla JS.
The title attribute to most tags is pretty smart about its position. I have added a title to one of the cells in the table in the jsFiddle (cell containing "Hello"). Is there any way to make my span exhibit the same smart behaviour?
A pop-up can be added before any element by putting the popup html code inside a 'div' with 'position:absolute; overflow:visible; width:0; height:0'.
When these events: 'onmouseenter', 'onmouseleave' are fired on the element, just toggle the popup css attribute 'display' between 'none' and 'block' of the element.
Example on jsfiddle:
https://jsfiddle.net/johnlowvale/mfLhw266/
HTML and JS:
<div class="popup-holder">
<div class="popup" id="popup-box">Some content</div>
</div>
Some link
<script>
function show_popup() {
var e = $("#popup-box");
e.css("display", "block");
}
function hide_popup() {
var e = $("#popup-box");
e.css("display", "none");
}
</script>
CSS:
.popup-holder {
position: absolute;
overflow: visible;
width: 0;
height: 0;
}
.popup {
background-color: white;
border: 1px solid black;
padding: 10px;
border-radius: 10px;
position: relative;
top: 20px;
width: 300px;
display: none;
}

Get dimensions of text block via JavaScript, not the size of container's `getBoundingClientRect`

I want to get the size of text inside a container. Let's consider general case when the container has padding and border.
The problem is that getBoundingClientRect returns the size of text PLUS left border and padding, in case the text overflows. Otherwise it returns just the size of border box of the container.
You can get the width if you create a placeholder div with all of the same text formatting options and find it's width.
For instance, I will create a div with the class .hidden that has the same attributes as the original div.
div.container
{
font-size: 16px;
}
div.hidden
{
font-size: 16px;
display: none;
}
Then, using jQuery, copy the contents of .container to .hidden and find the width of .hidden:
$(function(){
$("div.container").each(function(){
$("body").append("<div class='hidden'>"+$(this).html()+"</div>");
var width = $("div.hidden").width();
$("div.width").html("Actual width: "+width+"px");
$("div.hidden").remove();
});
});
JSFiddle
Interesting! You could use javascript to clone the text inside of an empty element offscreen that has 0 padding/margin/border. Then you could get the width of that element.
var txt = document.getElementById('fixed').innerHTML,
clone = document.getElementById('clone');
clone.innerHTML = txt;
var width = clone.offsetWidth;
document.getElementById('output').innerHTML = width;
#fixed {
width: 8em;
height: 8em;
border: .5em solid red;
}
#clone {
margin: 0;
padding: 0;
border: 0;
position: fixed;
left: -9999px;
}
<div id="fixed">asdfkjahsdflkahjsdflkjhasdljfhalsdkjfhalsdkjfhalsdkjfhalksdhjflasd</div>
<div id="clone"></div>
Width of text: <span id="output"></span>
People who had answered here came with a brilliant idea of wrapping the text into a <div> having zero margin, border and padding;
I just developed the idea further. I place the div inside the container, making the text have exactly the same style as it had without wrapper.
JsFiddle
This solution will work almost everywhere. It can be broken by not very encouraged way of writing CSS, like
.container div b {
padding: 5px; /* firing only when test is run */
}
If you do not code CSS in you project like that, you are the lucky one to use my snippet )

Why the container div height was not updated?

I'm adding elements into a container div whose height is 'auto' initially. I expect its height will be updated as the children elements appended. But, actually not. Could someone help me? I just want the container div height gets updated according to the children's height.
I used chrome debuging tool, the height of container div is less than height of children divs. Children divs are float:left.
If you're adding floated children to a div you need to have overflow:auto; on the parent.
You can also use another element to clear the float clear:both will do this.
This is because floated elements are taken out of the document flow.
Here's an example that shows you a few techniques you can use : http://jsfiddle.net/Tn5c3/
The CSS
#a, #b {
padding: 10px;
margin:10xp
}
#a {
background: #aa0000;
}
#b {
background: #00aa00;
overflow: auto;
}
p {
background: #0000aa;
padding: 5px;
}
.clear {
clear:both;
height: 50px;
}
The JS
$('#bb').click(function() {
addChild($('#b'));
});
$('#ba').click(function() {
addChild($('#a'));
});
function addChild(parent) {
var child = $('<p>floated para</p>').css({
'float': 'left'
});
parent.append(child);
}
The HTML
<button id='ba'>Add to A</button>
<button id='bb'>Add to B</button>
<div id='a'></div>
<div class='clear'></div>
<div id='b'></div>

How do I achieve equal height divs (positioned side by side) with HTML / CSS ?

I have two divs inside of a container. One on the left, one on the right, side by side. How am I able to make each one be of equal height, even though they have different content.
For example, the right div has a lot of content, and is double the height of the left div, how do I make the left div stretch to the same height of the right div?
Is there some JavaScript (jQuery) code to accomplish this?
You could use jQuery, but there are better ways to do this.
This sort of question comes up a lot and there are generally 3 answers...
1. Use CSS
This is the 'best' way to do it, as it is the most semantically pure approach (without resorting to JS, which has its own problems). The best way is to use the display: table-cell and related values. You could also try using the faux background technique (which you can do with CSS3 gradients).
2. Use Tables
This seems to work great, but at the expense of having an unsemantic layout. You'll also cause a stir with purists. I have all but avoided using tables, and you should too.
3. Use jQuery / JavaScript
This benefits in having the most semantic markup, except with JS disabled, you will not get the effect you desire.
Here's a way to do it with pure CSS, however, as you'll notice in the example (which works in IE 7 and Firefox), borders can be difficult - but they aren't impossible, so it all depends what you want to do. This example assumes a rather common CSS structure of body > wrapper > content container > column 1 and column 2.
The key is the bottom margin and its canceling padding.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Equal Height Columns</title>
<style type="text/css">
<!--
* { padding: 0; margin: 0; }
#wrapper { margin: 10px auto; width: 600px; }
#wrapper #main_container { width: 590px; padding: 10px 0px 10px 10px; background: #CCC; overflow: hidden; border-bottom: 10px solid #CCC; }
#wrapper #main_container div { float: left; width: 263px; background: #999; padding: 10px; margin-right: 10px; border: 1px solid #000; margin-bottom: -1000px; padding-bottom: 1000px; }
#wrapper #main_container #right_column { background: #FFF; }
-->
</style>
</head>
<body>
<div id="wrapper">
<div id="main_container">
<div id="left_column">
<p>I have two divs inside of a container. One on the left, one on the right, side by side. How am I able to make each one be of equal height, even though they have different content.</p>
</div><!-- LEFT COLUMN -->
<div id="right_column">
<p>I have two divs inside of a container. One on the left, one on the right, side by side. How am I able to make each one be of equal height, even though they have different content.</p>
<p> </p>
<p>For example, the right div has a lot of content, and is double the height of the left div, how do I make the left div stretch to the same height of the right div?</p>
<p> </p>
<p>Is there some JavaScript (jQuery) code to accomplish this?</p>
</div><!-- RIGHT COLUMN -->
</div><!-- MAIN CONTAINER -->
</div><!-- WRAPPER -->
</body>
</html>
This is what it looks like:
you can get it working with js:
<script>
$(document).ready(function() {
var height = Math.max($("#left").height(), $("#right").height());
$("#left").height(height);
$("#right").height(height);
});
</script>
I've seen many attempts to do this, though none met my OCD needs. You might need to dedicate a second to get your head around this, though it is better than using JavaScript.
Known downsides:
Does not support multiple element rows in case of a container with dynamic width.
Does not work in IE6.
The base:
red is (auxiliary) container that you would use to set margin to the content.
green is position: relative; overflow: hidden and (optionally, if you want columns to be centered) text-align: center; font-size: 0; line-height: 0;
blue display: block; float: left; or (optionally, if you want columns to be centered) display: inline-block; vertical-align: top;
So far nothing out of ordinary. Whatever content that blue element has, you need to add an absolutely positioned element (yellow; note that the z-index of this element must be lower than the actual content of the blue box) with this element and set top: 0; bottom: 0; (don't set left or right position).
All your elements now have equal height. For most of the layouts, this is already sufficient. My scenario required to have dynamic content followed by a static content, where static content must be on the same line.
To achieve this, you need to add padding-bottom (dark green) eq to the fixed height content to the blue elements.
Then within the yellow elements create another absolutely positioned (left: 0; bottom: 0;) element (dark blue).
Supposedly, if these boxes (yellow) had to be active hyperlinks and you had any style that you wanted to apply to the original blue boxes, you'd use adjacent sibling selector:
yellow:hover + blue {}
Here is a the code and demo:
HTML:
<div id="products">
<ul>
<li class="product a">
<a href="">
<p class="name">Ordinary product description.</p>
<div class="icon-product"></div>
</a>
<p class="name">Ordinary product description.</p>
</li>
<li class="product b">
<a href="">
<p class="name">That lenghty product description or whatever else that does not allow you have fixed height for these elements.</p>
<div class="icon-product"></div>
</a>
<p class="name">That lenghty product description or whatever else that does not allow you have fixed height for these elements.</p>
</li>
<li class="product c">
<a href="">
<p class="name">Another ordinary product description.</p>
<div class="icon-product"></div>
</a>
<p class="name">Another ordinary product description.</p>
</li>
</ul>
</div>
SCSS/LESS:
#products {
ul { position: relative; overflow: hidden; text-align: center; font-size: 0; line-height: 0; padding: 0; margin: 0;
li { display: inline-block; vertical-align: top; width: 130px; padding: 0 0 130px 0; margin: 0; }
}
li {
a { display: block; position: absolute; width: 130px; background: rgba(255,0,0,.5); z-index: 3; top: 0; bottom: 0;
.icon-product { background: #ccc; width: 90px; height: 90px; position: absolute; left: 20px; bottom: 20px; }
.name { opacity: 1; }
}
.name { position: relative; margin: 20px 10px 0; font-size: 14px; line-height: 18px; opacity: 0; }
a:hover {
background: #ddd; text-decoration: none;
.icon-product { background: #333; }
}
}
}
Note, that the demo is using a workaround that involves data-duplication to fix z-index. Alternatively, you could use pointer-events: none and whatever solution for IE.
here is very simple solution with a short css display:table
<div id="main" class="_dt-no-rows">
<div id="aside" contenteditable="true">
Aside
<br>
Here's the aside content
</div>
<div id="content" contenteditable="true">
Content
<br>
geht's pellentesque wurscht elementum semper tellus s'guelt Pfourtz !. gal hopla
<br>
TIP : Just clic on this block to add/remove some text
</div>
</div>
here is css
#main {
display: table;
width: 100%;
}
#aside, #content {
display: table-cell;
padding: 5px;
}
#aside {
background: none repeat scroll 0 0 #333333;
width: 250px;
}
#content {
background: none repeat scroll 0 0 #E69B00;
}
its look like this
Well, I don't do a ton of jQuery, but in the CSS/Javascript world I would just use the object model and write a statement as follows:
if(leftDiv.style.height > rightDive.style.height)
rightDiv.style.height = leftDiv.style.height;
else
leftDiv.style.height = rightDiv.style.height)
There's also a jQuery plugin called equalHeights that I've used with some success.
I'm not sure if the one I'm using is the one from the filament group mentioned above, or if it's this one that was the first google result... Either way a jquery plugin is probably the easiest, most flexible way to go.
Use this in jquery document ready function. Considering there are two divs having ids "left" and "right."
var heightR = $("#right").height();
var heightL = $("#left").height();
if(heightL > heightR){
$("#right").css({ height: heightL});
} else {
$("#left").css({ height: heightR});
}
Although many disagree with using javascript for this type of thing, here is a method that I used to acheive this using javascript alone:
var rightHeight = document.getElementById('right').clientHeight;
var leftHeight = document.getElementById('left').clientHeight;
if (leftHeight > rightHeight) {
document.getElementById('right').style.height=leftHeight+'px';
} else {
document.getElementById('left').style.height=rightHeight+'px';
}
With "left" and "right" being the id's of the two div tags.
This is what I use in plain javascript:
Seems long, but is very uncomplicated!
function equalizeHeights(elements){
//elements as array of elements (obtain like this: [document.getElementById("domElementId"),document.getElementById("anotherDomElementId")]
var heights = [];
for (var i=0;i<elements.length;i++){
heights.push(getElementHeight(elements[i],true));
}
var maxHeight = heights[biggestElementIndex(heights)];
for (var i=0;i<elements.length;i++){
setElementHeight(elements[i],maxHeight,true);
}
}
function getElementHeight(element, isTotalHeight){
// isTotalHeight triggers offsetHeight
//The offsetHeight property is similar to the clientHeight property, but it returns the height including the padding, scrollBar and the border.
//http://stackoverflow.com/questions/15615552/get-div-height-with-plain-javascript
{
isTotalHeight = typeof isTotalHeight !== 'undefined' ? isTotalHeight : true;
}
if (isTotalHeight){
return element.offsetHeight;
}else{
return element.clientHeight;
}
}
function setElementHeight(element,pixelHeight, setAsMinimumHeight){
//setAsMinimumHeight: is set, we define the minimum height, so it can still become higher if things change...
{
setAsMinimumHeight = typeof setAsMinimumHeight !== 'undefined' ? setAsMinimumHeight : false;
}
var heightStr = "" + pixelHeight + "px";
if (setAsMinimumHeight){
element.style.minHeight = heightStr; // pixels
}else{
element.style.height = heightStr; // pixels
}
}
function biggestElementIndex(arr){
//http://stackoverflow.com/questions/11301438/return-index-of-greatest-value-in-an-array
var max = arr[0];
var maxIndex = 0;
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max) {
maxIndex = i;
max = arr[i];
}
}
return maxIndex;
}
I agree with initial answer but the JS solution with equal_heights() method does not work in some situations, imagine you have products next to each other. If you were to apply it only to the parent container yes they will be same height but the product name sections might differ if one does not fit to two line, this is where i would suggest using below
https://jsfiddle.net/0hdtLfy5/3/
function make_children_same_height(element_parent, child_elements) {
for (i = 0; i < child_elements.length; i++) {
var tallest = 0;
var an_element = child_elements[i];
$(element_parent).children(an_element).each(function() {
// using outer height since that includes the border and padding
if(tallest < $(this).outerHeight() ){
tallest = $(this).outerHeight();
}
});
tallest = tallest+1; // some weird shit going on with half a pixel or something in FF and IE9, no time to figure out now, sowwy, hence adding 1 px
$(element_parent).children(an_element).each(function() {
$(this).css('min-height',tallest+'px');
});
}
}

Categories

Resources