Rectangle 27 141

3. display:inline block with a negative margin hack.

A common solution to this problem uses absolute positioning or cropped floats, but these are tricky in that they require extensive tuning if your columns change in number+size, and that you need to make sure your "main" column is always the longest. Instead, I'd suggest you use one of three more robust solutions:

display: flex

the simplest & best solution

table
display: table
  • display: inline-block; width:50% with a negative margin hack: quite simple, but column-bottom borders are a little tricky.

This is really simple, and it's easy to adapt to more complex or more detailed layouts - but flexbox is only supported by IE10 or later (in addition to other modern browsers).

.parent { display: -ms-flex; display: -webkit-flex; display: flex; }
.parent>div { flex:1; }

Flexbox has support for a lot more options, but to simply have any number of columns the above suffices!

A simple & extremely compatible way to do this is to use a table - I'd recommend you try that first if you need old-IE support. You're dealing with columns; divs + floats simply aren't the best way to do that (not to mention the fact that multiple levels of nested divs just to hack around css limitations is hardly more "semantic" than just using a simple table). If you do not wish to use the table element, consider css display: table (unsupported by IE7 and older).

Relevant html: (but consider using a plain <table> instead)

<div class="parent"><div>column 1</div><div>column 2</div></div>
.parent { display: table; }
.parent > div {display: table-cell; width:50%; }
/*omit width:50% for auto-scaled column widths*/

This approach is far more robust than using overflow:hidden with floats. You can add pretty much any number of columns; you can have them auto-scale if you want; and you retain compatibility with ancient browsers. Unlike the float solution requires, you also don't need to know beforehand which column is longest; the height scales just fine.

KISS: don't use float hacks unless you specifically need to. If IE7 is an issue, I'd still pick a plain table with semantic columns over a hard-to-maintain, less flexible trick-CSS solution any day.

By the way, if you need your layout to be responsive (e.g. no columns on small mobile phones) you can use a @media query to fall back to plain block layout for small screen widths - this works whether you use <table> or any other display: table element.

display:inline block

Relevant html: (the absence of spaces between the div tags is significant!)

<div class="parent"><div><div>column 1</div></div><div><div>column 2</div></div></div>
.parent { 
    position: relative; width: 100%; white-space: nowrap; overflow: hidden; 
}

.parent>div { 
    display:inline-block; width:50%; white-space:normal; vertical-align:top; 
}

.parent>div>div {
    padding-bottom: 32768px; margin-bottom: -32768px; 
}

This is slightly tricky, and the negative margin means that the "true" bottom of the columns is obscured. This in turn means you can't position anything relative to the bottom of those columns because that's cut off by overflow: hidden. Note that in addition to inline-blocks, you can achieve a similar effect with floats.

TL;DR: use flexbox if you can ignore IE9 and older; otherwise try a (css) table. If neither of those options work for you, there are negative margin hacks, but these can cause weird display issues that are easy to miss during development, and there are layout limitations you need to be aware of.

Good one, but it's worth to note that you're unable to use margins between these cells (and padding won't help if you want them styled).

border-spacing:10px; on the table element will introduce margin-like spacing. Alternatively, you could add extra (empty) columns where you want extra space. And you could also add padding inside the table-cells; that padding will be included in the background however, so that may not be what you want. But you're right that it's not quite as flexible as a normal margin. And you can't position anything relative to the columns, which may be a problem.

So it's better a table-less layout or not ?

I have to say: I agree to you that in this case a simple table is more than enough. The problem is that there is a common view to disregard every layout with table

The problem with table is that when the screen is resized to a smaller width (responsive design) the table cells get squished instead of tiling one over the top of the next one. The second method with padding-bottom: 32768px; margin-bottom: -32768px; is quite amazing and does almost exactly what I needed...thanks for that one...border bottom is an issue though...

html - CSS - Expand float child DIV height to parent's height - Stack ...

html css layout
Rectangle 27 141

3. display:inline block with a negative margin hack.

A common solution to this problem uses absolute positioning or cropped floats, but these are tricky in that they require extensive tuning if your columns change in number+size, and that you need to make sure your "main" column is always the longest. Instead, I'd suggest you use one of three more robust solutions:

display: flex

the simplest & best solution

table
display: table
  • display: inline-block; width:50% with a negative margin hack: quite simple, but column-bottom borders are a little tricky.

This is really simple, and it's easy to adapt to more complex or more detailed layouts - but flexbox is only supported by IE10 or later (in addition to other modern browsers).

.parent { display: -ms-flex; display: -webkit-flex; display: flex; }
.parent>div { flex:1; }

Flexbox has support for a lot more options, but to simply have any number of columns the above suffices!

A simple & extremely compatible way to do this is to use a table - I'd recommend you try that first if you need old-IE support. You're dealing with columns; divs + floats simply aren't the best way to do that (not to mention the fact that multiple levels of nested divs just to hack around css limitations is hardly more "semantic" than just using a simple table). If you do not wish to use the table element, consider css display: table (unsupported by IE7 and older).

Relevant html: (but consider using a plain <table> instead)

<div class="parent"><div>column 1</div><div>column 2</div></div>
.parent { display: table; }
.parent > div {display: table-cell; width:50%; }
/*omit width:50% for auto-scaled column widths*/

This approach is far more robust than using overflow:hidden with floats. You can add pretty much any number of columns; you can have them auto-scale if you want; and you retain compatibility with ancient browsers. Unlike the float solution requires, you also don't need to know beforehand which column is longest; the height scales just fine.

KISS: don't use float hacks unless you specifically need to. If IE7 is an issue, I'd still pick a plain table with semantic columns over a hard-to-maintain, less flexible trick-CSS solution any day.

By the way, if you need your layout to be responsive (e.g. no columns on small mobile phones) you can use a @media query to fall back to plain block layout for small screen widths - this works whether you use <table> or any other display: table element.

display:inline block

Relevant html: (the absence of spaces between the div tags is significant!)

<div class="parent"><div><div>column 1</div></div><div><div>column 2</div></div></div>
.parent { 
    position: relative; width: 100%; white-space: nowrap; overflow: hidden; 
}

.parent>div { 
    display:inline-block; width:50%; white-space:normal; vertical-align:top; 
}

.parent>div>div {
    padding-bottom: 32768px; margin-bottom: -32768px; 
}

This is slightly tricky, and the negative margin means that the "true" bottom of the columns is obscured. This in turn means you can't position anything relative to the bottom of those columns because that's cut off by overflow: hidden. Note that in addition to inline-blocks, you can achieve a similar effect with floats.

TL;DR: use flexbox if you can ignore IE9 and older; otherwise try a (css) table. If neither of those options work for you, there are negative margin hacks, but these can cause weird display issues that are easy to miss during development, and there are layout limitations you need to be aware of.

Good one, but it's worth to note that you're unable to use margins between these cells (and padding won't help if you want them styled).

border-spacing:10px; on the table element will introduce margin-like spacing. Alternatively, you could add extra (empty) columns where you want extra space. And you could also add padding inside the table-cells; that padding will be included in the background however, so that may not be what you want. But you're right that it's not quite as flexible as a normal margin. And you can't position anything relative to the columns, which may be a problem.

So it's better a table-less layout or not ?

I have to say: I agree to you that in this case a simple table is more than enough. The problem is that there is a common view to disregard every layout with table

The problem with table is that when the screen is resized to a smaller width (responsive design) the table cells get squished instead of tiling one over the top of the next one. The second method with padding-bottom: 32768px; margin-bottom: -32768px; is quite amazing and does almost exactly what I needed...thanks for that one...border bottom is an issue though...

html - CSS - Expand float child DIV height to parent's height - Stack ...

html css layout
Rectangle 27 13

My solution was to wrap the table inside a div with the negative margin.

<div style="margin-right:-20px">
  <table style="width:100%">
     ...
  </table>
</div>

Had given up on using div to automatically resize and position the elements of my page. Doing a table with width 100% and then having cells occupy the height and width of the margins will actually do the job nicely to my child div.

CSS Table width - 100% + minus margin - Stack Overflow

css
Rectangle 27 13

My solution was to wrap the table inside a div with the negative margin.

<div style="margin-right:-20px">
  <table style="width:100%">
     ...
  </table>
</div>

Had given up on using div to automatically resize and position the elements of my page. Doing a table with width 100% and then having cells occupy the height and width of the margins will actually do the job nicely to my child div.

CSS Table width - 100% + minus margin - Stack Overflow

css
Rectangle 27 54

Working only with css you can add a padding to the anchored element (as in a solution above) To avoid unnecessary whitespace you can add a negative margin of the same height:

#anchor {
    padding-top: 50px;
    margin-top: -50px;
}

I am not sure if this is the best solution in any case, but it works fine for me.

if there's a link within 50px above it, it may be covered up and made unclickable I believe

position: relative
position: relative; top: -50px;

@AleksDorohovich - You could post that as a separate answer since it's unique to the existing ones.

javascript - Make anchor link go some pixels above where it's linked t...

javascript html css anchor
Rectangle 27 53

Working only with css you can add a padding to the anchored element (as in a solution above) To avoid unnecessary whitespace you can add a negative margin of the same height:

#anchor {
    padding-top: 50px;
    margin-top: -50px;
}

I am not sure if this is the best solution in any case, but it works fine for me.

if there's a link within 50px above it, it may be covered up and made unclickable I believe

position: relative
position: relative; top: -50px;

@AleksDorohovich - You could post that as a separate answer since it's unique to the existing ones.

javascript - Make anchor link go some pixels above where it's linked t...

javascript html css anchor
Rectangle 27 50

Working only with css you can add a padding to the anchored element (as in a solution above) To avoid unnecessary whitespace you can add a negative margin of the same height:

#anchor {
    padding-top: 50px;
    margin-top: -50px;
}

I am not sure if this is the best solution in any case, but it works fine for me.

if there's a link within 50px above it, it may be covered up and made unclickable I believe

position: relative
position: relative; top: -50px;

@AleksDorohovich - You could post that as a separate answer since it's unique to the existing ones.

javascript - Make anchor link go some pixels above where it's linked t...

javascript html css anchor
Rectangle 27 1

as Gareth already mentioned, margins do not affect the box size. The solution is rather simple. The outer container needs to be 400px, this is what is going to trigger the horizontal scroll bars. The inner container needs to be 200px with 100px left and right margins. When you resize the window, the scroll bars appear as soon as you have gotten smaller than the outer container.

@Brent- That's not what I'm trying to accomplish. The whole point is I want the scrollbars to trigger only at the 200px width, and be ignored for the 400px width, though looks like this might be impossible...

Umm. Why set anything to 400px then? If you want scrollbars at 200px only, then make the wrapper that size. You should update your questions so it does not say you want them at 400px so anyone else that sees this doesn't get confused.

@Brent- It's for the sake of having an overflowing background that doesn't affect the layout. In any case, I'm not looking for an alternative solution, just an explanation of how neg margins affect the layout in this case.

html - Why do negative margins affect my page width? - Stack Overflow

html css layout
Rectangle 27 12

There was a solution I saw at A List Apart (I think), where you give the two inner columns a huge bottom padding, but the same huge value as a negative margin. This all works as long as the column is not more than 32000px high, which is rare. Something like:

.col {
  float: left;
  padding-bottom: 32000px;
  margin-bottom: -32000px;
}

...where "col" is the class name for any column. You can then style individual columns however you like with a separate class.

<div class="col xxx">x<br />x<br />x</div>
<div class="col yyy">y</div>

Another option is to use a background image on the outer div, including your borders etc. This approach obviously means it's a little more difficult to changes the columns (widths, colors) once set up.

After I set overflow: hidden on the container this worked for me (IE 7-9 & FF).

Very nice, but not quite there! If I apply a border or rounded corners to the inner divs, that is chopped off at the bottom.

css - How to make floating inner divs the same height as the highest d...

css html css-float height
Rectangle 27 1

OK, I found the solutionuse leftinstead of margin-left (still with a negative value, of course This removes the need to float the bulletted element, solving the collapsing margin issue.

.linked-list-item {
    background: url(http://cdn.donaldjenkins.com/media/icons/bullets/link-icon-black-16x16.jpg) no-repeat 0 2px;
    padding-left: 25px;
    left: -25px; /* IE6/7 position the element wrongly if you don't add 'position:relative' */
    position: relative;
}

And this is what it results in for IE6:

As you can see, the 26px margin for the element below the bulleted heading has reappeared. Anyone who doesn't want to go to the same extremes as me and doesn't need data URLs can actually use this code everywhereit works in modern browsers too.

Edit February 26, 2012: Running a data-url based bullet style for modern browsers side by side with the above code, as I did on my site, required me to add the following two attributes to the above code, so that I have two sets of code running in parallel:

<!-- 1. Modern browsers -->

.linked-list-item {
    background:url(data:image/png;base64[morecode]) no-repeat 0 4px;
    padding-left:25px;
    margin-left:-25px
}

<!-- 2. Targets IE6/7 only -->

.lt-ie8 .linked-list-item {
    background: url(http://cdn.donaldjenkins.com/media/icons/bullets/link-icon-black-16x16.jpg) no-repeat 0 2px;
    padding-left: 25px;
    left: -25px; /* IE6/7 position the element wrongly if you don't add 'position:relative' */
    position: relative;

<!-- a. Ensures background image is always visible in IE6 -->
    height: 100%;

<!-- b. Offsets the -25px negative margin in the modern browsers code -->
    margin-left: 0;
}

css - Issues with using a negative margin in background images to disp...

css css-float background-image internet-explorer-6 margin
Rectangle 27 9

Each negative sign in the proposed bottleneck solution

-bottleneck.partsort(-a, 10)[:10]

makes a copy of the data. We can remove the copies by doing

bottleneck.partsort(a, a.size-10)[-10:]

Also the proposed numpy solution

a.argsort()[-10:]

returns indices not values. The fix is to use the indices to find the values:

a[a.argsort()[-10:]]

The relative speed of the two bottleneck solutions depends on the ordering of the elements in the initial array because the two approaches partition the data at different points.

In other words, timing with any one particular random array can make either method look faster.

Averaging the timing across 100 random arrays, each with 1,000,000 elements, gives

-bn.partsort(-a, 10)[:10]: 1.76 ms per loop
bn.partsort(a, a.size-10)[-10:]: 0.92 ms per loop
a[a.argsort()[-10:]]: 15.34 ms per loop

where the timing code is as follows:

import time
import numpy as np
import bottleneck as bn

def bottleneck_1(a):
    return -bn.partsort(-a, 10)[:10]

def bottleneck_2(a):
    return bn.partsort(a, a.size-10)[-10:]

def numpy(a):
    return a[a.argsort()[-10:]]

def do_nothing(a):
    return a

def benchmark(func, size=1000000, ntimes=100):
    t1 = time.time()
    for n in range(ntimes):
        a = np.random.rand(size)
        func(a)
    t2 = time.time()
    ms_per_loop = 1000000 * (t2 - t1) / size
    return ms_per_loop

t1 = benchmark(bottleneck_1)
t2 = benchmark(bottleneck_2)
t3 = benchmark(numpy)
t4 = benchmark(do_nothing)

print "-bn.partsort(-a, 10)[:10]: %0.2f ms per loop" % (t1 - t4)
print "bn.partsort(a, a.size-10)[-10:]: %0.2f ms per loop" % (t2 - t4)
print "a[a.argsort()[-10:]]: %0.2f ms per loop" % (t3 - t4)

python - A fast way to find the largest N elements in an numpy array -...

python sorting numpy
Rectangle 27 3

Best solution is to put a div into table cell with zero width. Tbody table cells will inherit their widths from widths defined the thead. Position:relative and negative margin should do the trick!

<body>
<!-- SOME CSS -->
<style>
    .cropped-table-cells,
    .cropped-table-cells tr td { 
        margin:0px;
        padding:0px;
        border-collapse:collapse;
    }
    .cropped-table-cells tr td {
        border:1px solid lightgray;
        padding:3px 5px 3px 5px;
    }
    .no-overflow {
        display:inline-block;
        white-space:nowrap;
        position:relative; /* must be relative */
        width:100%; /* fit to table cell width */
        margin-right:-1000px; /* technically this is a less than zero width object */
        overflow:hidden;
    }
</style>

<!-- CROPPED TABLE BODIES -->
<table class="cropped-table-cells">
    <thead>
        <tr>
            <td style="width:100px;" width="100"><span>ORDER<span></td>
            <td style="width:100px;" width="100"><span>NAME<span></td>
            <td style="width:200px;" width="200"><span>EMAIL</span></td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><span class="no-overflow">123</span></td>
            <td><span class="no-overflow">Lorem ipsum dolor sit amet, consectetur adipisicing elit</span></td>
            <td><span class="no-overflow">sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span></td>
    </tbody>
</table>
</body>

You should use both span and div, of course by having proper block settings for span declared in css. As I know, td should contain div as well.

html - Why does overflow:hidden not work in a ? - Stack Overflow

html css
Rectangle 27 80

Programming iOS6, by Matt Neuburg documents this exact problem, and I actually found that his solution feels a little better than the currently accepted answer. That solution, which works great, has a negative side effect of animating to the image before/after, and then jarringly replacing that page with the desired page. I felt like that was a weird user experience, and Matt's solution takes care of that.

__weak UIPageViewController* pvcw = pvc;
[pvc setViewControllers:@[page]
              direction:UIPageViewControllerNavigationDirectionForward
               animated:YES completion:^(BOOL finished) {
                   UIPageViewController* pvcs = pvcw;
                   if (!pvcs) return;
                   dispatch_async(dispatch_get_main_queue(), ^{
                       [pvcs setViewControllers:@[page]
                                  direction:UIPageViewControllerNavigationDirectionForward
                                   animated:NO completion:nil];
                   });
               }];

I have the same problem, it works!!!!

This should be the accepted answer. Thanks

I wonder why pvcw is __weak here. Can you please explain? :)

Can anyone provide a swift version of this? Please.

iphone - UIPageViewController, how do I correctly jump to a specific p...

iphone objective-c ios uipageviewcontroller
Rectangle 27 80

Programming iOS6, by Matt Neuburg documents this exact problem, and I actually found that his solution feels a little better than the currently accepted answer. That solution, which works great, has a negative side effect of animating to the image before/after, and then jarringly replacing that page with the desired page. I felt like that was a weird user experience, and Matt's solution takes care of that.

__weak UIPageViewController* pvcw = pvc;
[pvc setViewControllers:@[page]
              direction:UIPageViewControllerNavigationDirectionForward
               animated:YES completion:^(BOOL finished) {
                   UIPageViewController* pvcs = pvcw;
                   if (!pvcs) return;
                   dispatch_async(dispatch_get_main_queue(), ^{
                       [pvcs setViewControllers:@[page]
                                  direction:UIPageViewControllerNavigationDirectionForward
                                   animated:NO completion:nil];
                   });
               }];

I have the same problem, it works!!!!

This should be the accepted answer. Thanks

I wonder why pvcw is __weak here. Can you please explain? :)

Can anyone provide a swift version of this? Please.

iphone - UIPageViewController, how do I correctly jump to a specific p...

iphone objective-c ios uipageviewcontroller
Rectangle 27 80

Programming iOS6, by Matt Neuburg documents this exact problem, and I actually found that his solution feels a little better than the currently accepted answer. That solution, which works great, has a negative side effect of animating to the image before/after, and then jarringly replacing that page with the desired page. I felt like that was a weird user experience, and Matt's solution takes care of that.

__weak UIPageViewController* pvcw = pvc;
[pvc setViewControllers:@[page]
              direction:UIPageViewControllerNavigationDirectionForward
               animated:YES completion:^(BOOL finished) {
                   UIPageViewController* pvcs = pvcw;
                   if (!pvcs) return;
                   dispatch_async(dispatch_get_main_queue(), ^{
                       [pvcs setViewControllers:@[page]
                                  direction:UIPageViewControllerNavigationDirectionForward
                                   animated:NO completion:nil];
                   });
               }];

I have the same problem, it works!!!!

This should be the accepted answer. Thanks

I wonder why pvcw is __weak here. Can you please explain? :)

Can anyone provide a swift version of this? Please.

iphone - UIPageViewController, how do I correctly jump to a specific p...

iphone objective-c ios uipageviewcontroller
Rectangle 27 5

Here is a simple solution using negative margins and floats.

For the CSS, use the following:

@media screen and (max-width:600px) {
    .yellow {
        background: yellow;
        width: 100%;
        height: 300px;
        float:left;
        margin-top: 300px;
    }

    .red {
        background: red;
        width: 100%;
        height: 300px;
        float:left;
        margin-left: -100%;
    }
}

Your HTML remains the same as you posted.

Add a top margin to .yellow using margin-top: 300px (equal to the height of the red div).

For the red div, add a negative left margin of 100%.

This will force the red div to position itself over the yellow div, but since you have the yellow div a top margin, the yellow div pops out under the red div.

The trick is similar to that used for the Holy Grail 3-column layout design.

html - Change order of floated divs with CSS - Stack Overflow

html css responsive-design media-queries
Rectangle 27 41

Workaround: Regex for matching a string not containing a string

I have left the old answer here for reference, and it also explains the negative lookup solution.

The pre-defined negative filters do work, but it doesn't currently allow you to do NOT filters on the names in Chrome stable, only CONTAINS. This is a bug that has been fixed in Chrome Canary.

Once the change has been pushed to Chrome stable, you should be able to do loadMess to filter only for that name, and -loadMess to filter out that name and leave the rest, as it was previously.

^((?!YOUR_STRING).)*$
^((?!loadMess).)*$

I discovered that there is actually a bug with how DevTools deals with Regex in the Network panel. This means the workaround above doesn't work, despite it being valid.

The Network panel filters on Name and Path (as discovered from the source code), but it does two tests that are OR'ed. In the case above, if you have loadMess in the Name, but not in the Path (e.g. not the domain or directory), it's going to match on either. To clarify, true || false === true, which means it will only filter out loadMess if it's found in both the Name and Path.

I have created an issue in Chromium and have subsequently pushed a fix to be reviewed. This has subsequently been merged.

really complete explanation but it does not work... An example here: s31.postimg.org/53odofq23/Schermata_del_2016_07_22_15_17_59.png. I have Chrome version 52.0.2743.82 (64-bit)

@suikoy I've spent the last hour trying everything and can't see why it is failing. I tested in JavaScript and it works fine for me. There could be something dodgy with the Regex parser used in DevTools. I'm going to keep looking into this. In the meantime, I guess just use Chrome Canary.

in fact before writing here I did some test with regex but chrome behaviour is very strange and I surrendered.. Thanks anyway for support ;)

@suikoy I found the issue in the source code! I'm going to look into fixing it. It will be super cool if I manage to set things up and make a pull request. I'll keep you posted!

@HussienK It was fixed in 54.0.2832.2.

Chrome dev tool: any way to exclude each call containing a string with...

regex google-chrome networking google-chrome-devtools
Rectangle 27 73

Here's a responsive CSS solution, based on adding a large padding and an equally large negative margin to each column, then wrapping the entire row in in a class with overflow hidden.

.col{
    margin-bottom: -99999px;
    padding-bottom: 99999px;
    background-color:#ffc;
}

.col-wrap{  
    overflow: hidden;   
}

In response to a question, here's the same technique in Bootstrap 3, same principle, just update the class names in the Bootstap grid: http://jsfiddle.net/panchroma/bj4ys/embedded/result/

One drawback, the background is drawed and jsut hidden because of the overflow. Meaning if you render something else then a static color you dont see the bottom border. try it together with call well on each column.

If the elements have borders, this won't look right...right?

Yes, but if you're just letting the inner boxes grow vertically and cutting them off at some arbitrary height, then some boxes may grow past the outer box, cutting off the bottom border. Unless I misunderstood this solution.

css - Using twitter bootstrap 2.0 - How to make equal column heights? ...

css twitter-bootstrap
Rectangle 27 2

Why is this solution better than setting main content width?

The only requirement is that you must predefine your floated element's width. Then it can have whatever height you like and the non-floated content (when applied right margin) won't stretch under floated element.

  • We have floated element on the right with width = X
  • We have usual content but set its right margin = X+s where s is some predefined space between your content and floated element so they don't touch.

Since you have multiple content elements (heads, paragraphs) you have to put them inside a container with this right margin setting.

<div id="parent">
    <div id="floated">Foo bar</div>
    <div id="content">
        <h2>Foo</h2>
        <p>Text!</p>
    </div>
</div>
#floated
{
    float: right;
    padding: 1em;
    background: #ccc;
    width: 10em;
}

#content
{
    margin-right: 13em; /* 10em width + 2 x 1em padding + 1em space */
}

Because setting main content width will only work when you want to limit your document content to a fixed width (like 960 grid). But when you want your content to stretch over the whole browser window width, this solution will work regardless of browser window size.

Avoid using inline styles whenever possible because maintainability of your application/site will become a nightmare.

html - Css - Don't want elements below my floated element - Stack Over...

html css overflow css-float hidden
Rectangle 27 2

Why is this solution better than setting main content width?

The only requirement is that you must predefine your floated element's width. Then it can have whatever height you like and the non-floated content (when applied right margin) won't stretch under floated element.

  • We have floated element on the right with width = X
  • We have usual content but set its right margin = X+s where s is some predefined space between your content and floated element so they don't touch.

Since you have multiple content elements (heads, paragraphs) you have to put them inside a container with this right margin setting.

<div id="parent">
    <div id="floated">Foo bar</div>
    <div id="content">
        <h2>Foo</h2>
        <p>Text!</p>
    </div>
</div>
#floated
{
    float: right;
    padding: 1em;
    background: #ccc;
    width: 10em;
}

#content
{
    margin-right: 13em; /* 10em width + 2 x 1em padding + 1em space */
}

Because setting main content width will only work when you want to limit your document content to a fixed width (like 960 grid). But when you want your content to stretch over the whole browser window width, this solution will work regardless of browser window size.

Avoid using inline styles whenever possible because maintainability of your application/site will become a nightmare.

html - Css - Don't want elements below my floated element - Stack Over...

html css overflow css-float hidden