CSS: How can I center text despite a floating element beside it? - css

Basically, I want to center text, ignoring any floating sibling elements.
At first, I thought this wouldn't be a problem, as I was under the impression that a floating element did not take from the width of any sibling elements.
Example (I want the red text to be at the center of the blue box, despite the green text)
How is this best achieved?

You can't. If it were centered within the parent box, then the float would overlap the content at some point, which would be defeating the point of the float. There are two approaches you can use here. If you know the width of the float, you can apply an equal negative right margin. Otherwise, you can absolutely position the element like this.

Here's a link to a working fiddle: http://jsfiddle.net/cD657/3/
(in your example, you opened a <span>, and closed it with </div>)
I made it a div and gave it margin: 0px auto; and a width. -seemed to do the trick

You can keep as you have it but just adding padding on the opposite side with the same pixel value as the width of the floating element.
.parent{
text-align: center;
}
.centered.element{
padding-left: [width of floating element]px;
}
.floating.element{
float: left;
}
To find the width easily just use Developer Tools in any modern browser to Inspect the element.
See fiddle here: http://jsfiddle.net/cD657/369/
Note: This may not work if the centered element has an assigned background color.

Related

css vertical align using Floater Div. what's the benefit of using floater?

I am learning how to vertically align element and found one approach(Floater Div) here:
http://www.vanseodesign.com/css/vertical-centering/
**HTML**
<div id="parent">
<div id="floater"></div>
<div id="child">Content here</div>
</div>
**CSS**
#parent {height: 250px;}
#floater {
float: left;
height: 50%;
width: 100%;
margin-bottom: -50px;
}
#child {
clear: both;
height: 100px;
}
Why we need #floater to be floated? Deleting float:left and clear: both still works. What's the benefit of making it floated?
I know there are lots of ways to vertically align element, and seems each of them have some disadvantage like you need to know the height; old IE won't work; multiple lines won't work and so on. But for this approach it put one element to fill up the entire upper half of the parent element. I just wonder why this element need to be floater?
This might not be the best approach to vertically align elements.
For float:left, A floated element will move as far to the left or right as it can. Usually this means all the way to the left or right of the containing element. But in this case since there are no other elements in the document the floater div will start from left even without float:left
The clear property specifies which side(s) of an element other floating elements are not allowed.
clear: both - No floating elements allowed on either the left or the right side
Elements after the floating element will flow around it. To avoid this, we use the clear property.The clear property specifies which sides of an element other floating elements are not allowed.
This makes sure that the child element is not on either left or right of div, but clearing it does not make any changes, you are right, it might though in some cases.
This approach is though very restrictive as you have to know the hieght of child elements and also if there are more elements inside the parent div this will not work.
For much better methods of vertical alignment refer this question

Strange behavior on computed height and childrens margin

I want to know the real height of an element no matters what it have inside. That's easy. The problem began when I put away the borders of the element and notice an strange behavior, see it here:
http://jsfiddle.net/LypZR/
First div: 122px: OK (children height 100px, children margins 20px, border 2px)
.bordered {
border: 1px solid #000;
}
Second div: 120px: OK (children height 100px, children margins 20px)
.display-inline-block {
display: inline-block;
}
Thirth div: 100px: What? where are the margins?
I solved it using display: inline-block that works just fine for me (in this particular case). But I really want to know what is exactly happening.
I think you're getting surprised by margin collapsing.
The two cases that margins collapse are between adjacent sibling elements and between parent and child elements.
In your case, it's the parent/child collapse that's causing you grief: If you have nothing interesting between the top margin of your parent and the (top margin of its first child|bottom margin of its last child), the parent margin collapses. The transparent border hack is commonly-used in these cases.
You probably noted that it didn't change the actual layout values--the p tag's margin kept the visible elements from collapsing into each other. But I admit it's counterintuitive.
That's called the margin collapsing.
When the child element is given margin and parent element don't have any content in it, this happens.
add this class and its done.
.no-bordered{
overflow:auto;
}
Fiddle : http://jsfiddle.net/LypZR/3/
you can see real height without any collapse if you use the right css selector for all the elements *, so:
* {
height: 100px;
margin: 10px;
}
Like you did it's like a quirk behave for me because I don't know .element selector, and if you look inside the consolle could you see that no margin is applied in the styles tab, but only a computed height is calculated, perhaps for some strange behavior it isn't suppouse to work right. till I know only height width and padding are considerate for real element dimensions.
margins should not be considerate for real element dimensions, this is only an IE issue who do such calc adding margin to real element dimensions. jsfiddle

Making a div's overflow:hidden effective without positioning it

I have 3 divs:
(blue) containing div with position: relative
(red) div with overflow: hidden, floated left
(green) div with position: absolute that I want positioned relatively to the first div.
see jsfiddle.
I want the green div hidden outside the red div, so making the overflow: hidden work without positioning it, because I want the green one positioned relative to the blue one.
I found some similar questions, but none that really fit this same case.
You are on the right track, but you need to make the red div have relative positioning.
Right now, your green div is being positioned absolutely relative to the blue one, but as long as that is happening, it is bound by the overflow rules of the blue one, not the red one.
When you use absolute positioning, the positioned element is bound by the overflow of the nearest parent element with relative positioning, ultimately the window if no others exist.
.two{
background-color: red;
overflow: hidden;
float: left;
position:relative;
}
JSFiddle
I believe this is impossible using only css. You could make it look like what your talking about using javascript or jquery fairly easy, but I wasn't sure if you wanted an answer in that form.

Strange container div behaviour

I'm asking this for learning purposes; there aren't any negative aspects on this behaviour, but I just wonder if this could have any negative consequences in the future.
So I have a container div: content_wrap, which has two other div's: side_bar and main_content. The container div is 980px width, and is used to center its contents using margin-left and margin-right.
It's doing this correctly, however, when I was debugging the page (in Firefox), I noticed that the browser renders the div as being 0x0px and renders the parent div off-screen. However, it does position the child divs correctly. See this JSFiddle for an example: http://jsfiddle.net/7fsXp/7/
I Googled this and most of the answers have something to do with floats and are solved by using clear:both, but I don't use any floats. I did notice that if I change the main_content div from position:absolute; to position:relative;, the content_wrap is displayed correctly. Or I can fix it by setting a height for content_wrap.
I don't actually need to be able to see the content_wrap, so there isn't really a problem, as it is doing its job in means of centering the child divs. I just wondered if it would be a bad practice to leave it like this? Is it a bad thing, or does it matter?
Try adding other elements to this HTML and enjoy the horror :D
There are actually many things in your code, that I wouldn't do. First of all, when an element is with position: absolute or position: fixed its layout is "ignored" by other elements or in other words cannot "push" any element and that is why your container is having 0 height. It's like they are ethereal (best explanation ever, I know).
You should check this article on positioning -- http://css-tricks.com/absolute-relative-fixed-positioining-how-do-they-differ/
The fact that they are in the place you expect them to be is that there are actually no other elements in the HTML and the absolute element is positioned relatively to the body and so is the fixed one (but that's what elements with position: fixed always do). Looks what happens when I add some other content to the parent div -- http://jsfiddle.net/7fsXp/13/
So long story short - you shouldn't form your layout with absolute or fixed elements if you can do it without them.
position: fixed and position: absolute take the elements out of the flow, so using either of these positions on all child divs will collapse the parent div entirely.
If you have content below a collapsed div, it will flow up and over/under that content like this.
You don't need to position the main_content div absolutely, but you'll need to change a few things to top align the sidebar and main_content.
DEMO
Since sidebar is fixed, it's using the document, not the container div as a reference for top, while main_content would use the body (unless you add position: relative to the container). Getting rid of the body's default padding/margin will fix the small alignment difference.
body {
padding: 0;
margin: 0;
}
#main_content {
//remove position: absolute;
margin-top:70px; //top: 70px won't work unless you specify position
}
It depends on what you are willing to do, but because the default position for div is position: static; changing the position: relative; will avoid the collapse of parent div.

What is the difference between `margin` and `padding` in CSS?

What is the difference between margin and padding in CSS?
In what kind of situations:
both work.
only margin is appropriate.
only padding is appropriate.
TL;DR: By default I use margin everywhere, except when I have a border or background and want to increase the space inside that visible box.
To me, the biggest difference between padding and margin is that vertical margins auto-collapse, and padding doesn't.
Consider two elements one above the other each with padding of 1em. This padding is considered to be part of the element and is always preserved.
So you will end up with the content of the first element, followed by the padding of the first element, followed by the padding of the second, followed by the content of the second element.
Thus the content of the two elements will end up being 2em apart.
Now replace that padding with 1em margin. Margins are considered to be outside of the element, and margins of adjacent items will overlap.
So in this example, you will end up with the content of the first element followed by 1em of combined margin followed by the content of the second element. So the content of the two elements is only 1em apart.
This can be really useful when you know that you want to say 1em of spacing around an element, regardless of what element it is next to.
The other two big differences are that padding is included in the click region and background color/image, but not the margin.
div.box > div { height: 50px; width: 50px; border: 1px solid black; text-align: center; }
div.padding > div { padding-top: 20px; }
div.margin > div { margin-top: 20px; }
<h3>Default</h3>
<div class="box">
<div>A</div>
<div>B</div>
<div>C</div>
</div>
<h3>padding-top: 20px</h3>
<div class="box padding">
<div>A</div>
<div>B</div>
<div>C</div>
</div>
<h3>margin-top: 20px; </h3>
<div class="box margin">
<div>A</div>
<div>B</div>
<div>C</div>
</div>
Margin is on the outside of block elements while padding is on the inside.
Use margin to separate the block from things outside it
Use padding to move the contents away from the edges of the block.
The best I've seen explaining this with examples, diagrams, and even a 'try it yourself' view is here.
The diagram below I think gives an instant visual understanding of the difference.
One thing to keep in mind is standards compliant browsers (IE quirks is an exception) render only the content portion to the given width, so keep track of this in layout calculations. Also note that border box is seeing somewhat of a comeback with Bootstrap 3 supporting it.
There are more technical explanations for your question, but if you want a way to think about margin and padding, this analogy might help.
Imagine block elements as picture frames hanging on a wall:
The photo is the content.
The matting is the padding.
The frame moulding is the border.
The wall is the viewport.
The space between two frames is the margin.
With this in mind, a good rule of thumb is to use margin when you want to space an element in relationship to other elements on the wall, and padding when you're adjusting the appearance of the element itself. Margin won't change the size of the element, but padding will make the element bigger1.
1 You can alter this behavior with the box-sizing attribute.
MARGIN vs PADDING :
Margin is used in an element to create distance between that element and other elements of page. Where padding is used to create distance between content and border of an element.
Margin is not part of an element where padding is part of element.
Please refer below image extracted from Margin Vs Padding - CSS Properties
From https://www.w3schools.com/css/css_boxmodel.asp
Explanation of the different parts:
Content - The content of the box, where text and images appear
Padding - Clears an area around the content. The padding is transparent
Border - A border that goes around the padding and content
Margin - Clears an area outside the border. The margin is transparent
Live example (play around by changing the values):
https://www.w3schools.com/css/tryit.asp?filename=trycss_boxmodel
It's good to know the differences between margin and padding. Here are some differences:
Margin is outer space of an element, while padding is inner space of an element.
Margin is the space outside the border of an element, while padding is the space inside the border of it.
Margin accepts the value of auto: margin: auto, but you can't set padding to auto.
Tip: You can use the trick to make elements centered inside their parents (even vertically). See my other answer for example.
Margin can be set to any number, but padding must be non-negative.
When you style an element, padding will also be affected (e.g. background color), but not margin.
Here is some HTML that demonstrates how padding and margin affect clickability, and background filling. An object receives clicks to its padding, but clicks on an objects margin'd area go to its parent.
$(".outer").click(function(e) {
console.log("outer");
e.stopPropagation();
});
$(".inner").click(function(e) {
console.log("inner");
e.stopPropagation();
});
.outer {
padding: 10px;
background: red;
}
.inner {
margin: 10px;
padding: 10px;
background: blue;
border: solid white 1px;
}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<div class="outer">
<div class="inner" style="position:relative; height:0px; width:0px">
</div>
</div>
The thing about margins is that you don't need to worry about the element's width.
Like when you give something {padding: 10px;}, you'll have to reduce the width of the element by 20px to keep the 'fit' and not disturb other elements around it.
So I generally start off by using paddings to get everything 'packed' and then use margins for minor tweaks.
Another thing to be aware of is that paddings are more consistent on different browsers and IE doesn't treat negative margins very well.
The margin clears an area around an element (outside the border), but the padding clears an area around the content (inside the border) of an element.
it means that your element does not know about its outside margins, so if you are developing dynamic web controls, I recommend that to use padding vs margin if you can.
note that some times you have to use margin.
One thing to note is when auto collapsing margins annoy you (and you are not using background colours on your elements), something it's just easier to use padding.
Advanced Margin versus Padding Explained
It is inappropriate to use padding to space content in an element; you must utilize margin on the child element instead. Older browsers such as Internet Explorer misinterpreted the box model except when it came to using margin which works perfectly in Internet Explorer 4.
There are two exceptions when using padding is appropriate to use:
It is applied to an inline element which can not contain any child elements such as an input element.
You are compensating for a highly miscellaneous browser bug which a vendor *cough* Mozilla *cough* refuses to fix and are certain (to the degree that you hold regular exchanges with W3C and WHATWG editors) that you must have a working solution and this solution will not effect the styling of anything other then the bug you are compensating for.
When you have a 100% width element with padding: 50px; you effectively get width: calc(100% + 100px);. Since margin is not added to the width it will not cause unexpected layout problems when you use margin on child elements instead of padding directly on the element.
So if you're not doing one of those two things do not add padding to the element but to it's direct child/children element(s) to ensure you're going to get the expected behavior in all browsers.
First let's look at what are the differences and what each responsibility is:
1) Margin
The CSS margin properties are used to generate space around elements.
The margin properties set the size of the white space outside the
border. With CSS, you have full control over the margins. There are
CSS properties for setting the margin for each side of an element
(top, right, bottom, and left).
2) Padding
The CSS padding properties are used to generate space around content.
The padding clears an area around the content (inside the border) of
an element. With CSS, you have full control over the padding. There
are CSS properties for setting the padding for each side of an element
(top, right, bottom, and left).
So simply Margins are space around elements, while Padding are space around content which are part of the element.
This image from codemancers shows how margin and borders get togther and how border box and content-box make it different.
Also they define each section as below:
Content - this defines the content area of the box where the actual content like text, images or maybe other elements reside.
Padding - this clears the main content from its containing box.
Border - this surrounds both content and padding.
Margin - this area defines a transparent space that separates it from other elements.
I always use this principle:
This is the box model from the inspect element feature in Firefox. It works like an onion:
Your content is in the middle.
Padding is space between your content and edge of the tag it is
inside.
The border and its specifications
The margin is the space around the tag.
So bigger margins will make more space around the box that contains your content.
Larger padding will increase the space between your content and the box of which it is inside.
Neither of them will increase or decrease the size of the box if it is set to a specific value.
Margin
Margin is usually used to create a space between the element itself and its surround.
for example I use it when I'm building a navbar to make it sticks to the edges of the screen and for no white gap.
Padding
I usually use when I've an element inside a border, <div> or something similar, and I want to decrease its size but at the time I want to keep the distance or the margin between the other elements around it.
So briefly, it's situational; it depends on what you are trying to do.
Margin is outside the box and padding is inside the box

Resources