How to implement simple layout: header - sidebar - content - html

I'm looking for a simple, effective and modern way to implement the following layout for a website:
- header: 100% width
- below header
- sidebar with fixed width
- content area that fills up till 100%
I've found a good example here, but this is all based on 'em' sizing, we have quite some backgroundpixels so we rather need an example with 'px'.
We thought that we could switch easily to 'px' in that specific example, but apparently it's not that easy to get this perfect.
Thanks in advance for all the tips!

You can use flex to have a sidebar on the left with a fixed width whereas the content on the right takes up the remaining space. Be aware that flex was added with CSS3 and older versions of Internet explorer may not support it (http://caniuse.com/#search=flex)
.contentContainer {
display:flex;
flex-direction: row;
}
.left {
background-color: #ffaa00;
min-width:200px;
}
.right {
background-color: #00aaaa;
flex:1;
}
https://jsfiddle.net/nrv5p70q/1/
However some simple googling could have solved the issue too. You may want to check this cheat sheet:
https://css-tricks.com/snippets/css/a-guide-to-flexbox/

The example you are using will allow you to achieve this.
You can use a em to px conversion to convert the values from em to px. Once you have the correct values you can replace them in the css. Thus.
#nav {
margin-left: -352px; //was -22em
margin-left: expression((-(document.getElementById("wrapper").clientWidth))+"px");
left: 208px; //was 13em;
}
Using this method will allow you to continuing w3schools tutorial which is a great way to get up to speed with html and css.

Related

How to apply CSS style based on parent element, similar to media queries [duplicate]

I would like to use media queries to resize elements based on the size of a div element they are in. I cannot use the screen size as the div is just used like a widget within the webpage, and its size can vary.
Yes, CSS Container Queries are what you're looking for. The CSS Containment Module is the specification that details this feature.
You can read more about the decade of work, including proposals, proofs-of-concept, discussions and other contributions by the broader web developer community here! For more details on how such a feature might work and be used, check out Miriam Suzanne's extensive explainer.
Currently only Chromium 105+ supports Container queries out of the box, though Safari 16 will include support as well. Hopefully it won't be much longer before we see a robust cross-browser implementation of such a system. It's been a grueling wait, but I'm glad that it's no longer something we simply have to accept as an insurmountable limitation of CSS due to cyclic dependencies or infinite loops or what have you (these are still a potential issue in some aspects of the proposed design, but I have faith that the CSSWG will find a way).
Media queries aren't designed to work based on elements in a page. They are designed to work based on devices or media types (hence why they are called media queries). width, height, and other dimension-based media features all refer to the dimensions of either the viewport or the device's screen in screen-based media. They cannot be used to refer to a certain element on a page.
If you need to apply styles depending on the size of a certain div element on your page, you'll have to use JavaScript to observe changes in the size of that div element instead of media queries.
Alternatively, with more modern layout techniques introduced since the original publication of this answer such as flexbox and standards such as custom properties, you may not need media or element queries after all. Djave provides an example.
I've just created a javascript shim to achieve this goal. Take a look if you want, it's a proof-of-concept, but take care: it's a early version and still needs some work.
https://github.com/marcj/css-element-queries
From a layout perspective, it is possible using modern techniques.
Its made up (I believe) by Heydon Pickering. He details the process here: http://www.heydonworks.com/article/the-flexbox-holy-albatross
Chris Coyier picks it up and works through a demo of it here: https://css-tricks.com/putting-the-flexbox-albatross-to-real-use/
To restate the issue, below we see 3 of the same component, each made up of three orange divs labelled a, b and c.
The second two's blocks display vertically, because they are limited on horizontal room, while the top components 3 blocks are laid out horizontally.
It uses the flex-basis CSS property and CSS Variables to create this effect.
.panel{
display: flex;
flex-wrap: wrap;
border: 1px solid #f00;
$breakpoint: 600px;
--multiplier: calc( #{$breakpoint} - 100%);
.element{
min-width: 33%;
max-width: 100%;
flex-grow: 1;
flex-basis: calc( var(--multiplier) * 999 );
}
}
Demo
Heydon's article is 1000 words explaining it in detail, and I'd highly recommend reading it.
Update 2021/22
As mentioned in other answers, container queries are coming. There is a full spec for it, and its usage is detailed on MDN:
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Container_Queries
and there is a polyfill to get browsers that don't yet support it up to speed:
https://github.com/GoogleChromeLabs/container-query-polyfill
There is a nice little overview video of it here:
https://www.youtube.com/watch?v=gCNMyYr7F6w
This has now shipped to Chrome (05 September 2022)
https://caniuse.com/css-container-queries
A Media Query inside of an iframe can function as an element query. I've successfully implement this. The idea came from a recent post about Responsive Ads by Zurb. No Javascript!
This is currently not possible with CSS alone as #BoltClock wrote in the accepted answer, but you can work around that by using JavaScript.
I created a container query (aka element query) polyfill to solve this kind of issue. It works a bit different than other scripts, so you don’t have to edit the HTML code of your elements. All you have to do is include the script and use it in your CSS like so:
.element:container(width > 99px) {
/* If its container is at least 100px wide */
}
https://github.com/ausi/cq-prolyfill
I ran into the same problem a couple of years ago and funded the development of a plugin to help me in my work. I've released the plugin as open-source so others can benefit from it as well, and you can grab it on Github: https://github.com/eqcss/eqcss
There are a few ways we could apply different responsive styles based on what we can know about an element on the page. Here are a few element queries that the EQCSS plugin will let you write in CSS:
#element 'div' and (condition) {
$this {
/* Do something to the 'div' that meets the condition */
}
.other {
/* Also apply this CSS to .other when 'div' meets this condition */
}
}
So what conditions are supported for responsive styles with EQCSS?
Weight Queries
min-width in px
min-width in %
max-width in px
max-width in %
Height Queries
min-height in px
min-height in %
max-height in px
max-height in %
Count Queries
min-characters
max-characters
min-lines
max-lines
min-children
max-children
Special Selectors
Inside EQCSS element queries you can also use three special selectors that allow you to more specifically apply your styles:
$this (the element(s) matching the query)
$parent (the parent element(s) of the element(s) matching the query)
$root (the root element of the document, <html>)
Element queries allow you to compose your layout out of individually responsive design modules, each with a bit of 'self-awareness' of how they are being displayed on the page.
With EQCSS you can design one widget to look good from 150px wide all the way up to 1000px wide, then you can confidently drop that widget into any sidebar in any page using any template (on any site) and
The question is very vague. As BoltClock says, media queries only know the dimensions of the device. However, you can use media queries in combination with descender selectors to perform adjustments.
.wide_container { width: 50em }
.narrow_container { width: 20em }
.my_element { border: 1px solid }
#media (max-width: 30em) {
.wide_container .my_element {
color: blue;
}
.narrow_container .my_element {
color: red;
}
}
#media (max-width: 50em) {
.wide_container .my_element {
color: orange;
}
.narrow_container .my_element {
color: green;
}
}
The only other solution requires JS.
The only way I can think that you can accomplish what you want purely with css, is to use a fluid container for your widget. If your container's width is a percentage of the screen then you can use media queries to style depending on your container's width, as you will now know for each screen's dimensions what is your container's dimensions. For example, let's say you decide to make your container's 50% of the screen width. Then for a screen width of 1200px you know that your container is 600px
.myContainer {
width: 50%;
}
/* you know know that your container is 600px
* so you style accordingly
*/
#media (max-width: 1200px) {
/* your css for 600px container */
}
You can use the ResizeObserver API. It's still in it's early days so it's not supported by all browsers yet (but there's several polyfills that can help you with that).
This API allows you to attach an event listener when resizing a DOM element.
Demo 1 - Demo 2
I was also thinking of media queries, but then I found this:
http://www.mademyday.de/css-height-equals-width-with-pure-css.html
Maintain the aspect ratio of a div with CSS
Just create a wrapper <div> with a percentage value for padding-bottom, like this:
div {
width: 100%;
padding-bottom: 75%;
background:gold; /** <-- For the demo **/
}
<div></div>
It will result in a <div> with height equal to 75% of the width of its container (a 4:3 aspect ratio).
This technique can also be coupled with media queries and a bit of ad hoc knowledge about page layout for even more finer-grained control.
It's enough for my needs. Which might be enough for your needs too.
For mine I did it by setting the div's max width, hence for small widget won't get affected and the large widget is resized due to the max-width style.
// assuming your widget class is "widget"
.widget {
max-width: 100%;
height: auto;
}

apply css to specific elements

On my site I am using the theme Newspaper. I have modified it a bit with css. I am trying to get my sidebar (instagram, most popular, newsletter sign up) to have a width of 26% so it would be on the same row as the editor's picks.
The problem is that I can not get the sidebar to have a width of 26% without affecting the 3 blocks above editor's picks. Since both of them are .td-pb-span4. I have tried to solve this issue by using a more specific code just for the sidebar (code down below) and it still will not work. It is weird because the code I am trying to use will apply in chrome developer, however once I add it to my css it doesn't apply to my site. I would really appreciate any solution, I have been trying to figure this out for a few days and can't seem to find the problem.
code I first tried to add but it affected both the sidebar and the 3 blocks above editors picks (and I only want width:26% to apply to the sidebar)
.td-pb-span4 {
width: 26%;
}
more specific code I am trying to add that only applies to the sidebar (it will work in chrome developer, but will not work if I apply it to my site css)
.vc_column.td_uid_70_5976097f07941_rand.wpb_column.vc_column_container.td-pb-span4 {
width: 26%;
}
Don't do this:
/* index ~line 2817 */
.td-pb-span8 { /* WHY */
width: 70%;
float: left;
margin-right: 4%;
}
you're touching a well defined grid system that has to work out of the box:
.td-pb-span8 {
width: 66.66666667%; /* yep. There's no reason on earth you should set to 70% */
}
Grids are 12 based so do the math: 100 / 12 * 8

make div over another on liquid template

I'm trying to make two div's, one overlaps on another
As you can see on the fiddle below there is position:relative; top:-20px; And I would like to make it fully liquid without any px maybe on percentage, however I have no Idea how to make that.
Here's fiddle
I'm not sure what you mean by "fully liquid", but those position sub-values don't accept percentage values.
The best I could offer is to use
#first {
margin-bottom: -5%;
}
or
#second {
margin-top: -5%;
}
or some combination thereof.
Do you mean switching this line as in this fiddle:
//top:-20px;
margin-top:-3%;

Centering a div popup in the center of screen

I have searched a lot for centering a div, both horizontally and vertically, this is the method given everywhere:
div {
position:fixed;
top:50%;
left:50%;
margin-left:(div width/2)
margin-top: (div height/2)
}
I just found a new solution to centering a div, both horizontally and vertically, by wrapping it inside a table. I've tested it in ie7 and above, plus other browsers.
Here is an example : http://jsbin.com/ocenok/2/
I was wondering that the first method is found everywhere on the internet, SO, etc. and requires beforehand knowledge of width and height, or is usually calculated via Javascript.
The table approach seems flawless, and requires neither javascript, nor fixed height/width.
Are there any drawbacks to the table approach ?
(I do not know the height/width of the div that I want to center.)
Update (To make my question clearer) :
I myself hate using tables for non-tabular/layout data.
I know that what I want can easily be achieved using Javascript.
I figured I can achieve this using display:table, killing IE7 support.
But what I'm trying to understand is, that when I can achieve this using a single <table> element, what are the drawbacks, if any.
Checking Answers here and on similar questions, no one has recommended this method, even though it uses all valid HTML elements and syntax and rules.
If everyone is recommending to use javascript to handle presentation, even though it is easily possible using CSS, it must have some drawbacks.
Code :
<table>
<tr>
<td>
<div>This is div that needs to be centered.</div>
</td>
</tr>
</table>
and then apply the following CSS
table {
width:100%;
height:100%;
position:fixed;
top:0;
left:0;
}
table td {
width : 100%;
text-align: center;
}
div {
width:100px;
height:100px;
background:pink;
margin: 0 auto;
}
see the below function and change as per your needs
function positionLightboxImage() {
var top = ($(window).height() - $('#lightbox').height()) / 2;
var left = ($(window).width() - $('#lightbox').width()) / 2;
console.log("The calculated position is:");
console.log(top,left);
$('#lightbox')
.css({
'top': top + $(document).scrollTop(),
'left': left
})
.fadeIn();
console.log('A jQuery selection:');
console.log($('#lightbox'));
}
Updated answer HTML and CSS:
HTML:
<div id="outer"><div id="inner"></div></div>
CSS:
#outer {
position: absolute;
top: 50%;
left: 0px;
width: 100%;
height: 1px;
overflow: visible;
background:red;
}
#inner {
width: 300px;
height: 200px;
margin-left: -150px; /*** width / 2 ***/
position: absolute;
top: -100px; /*** height / 2 ***/
left: 50%;
background:#ccc;
}
Even more updated using jquery and always remain center when you resize the window too : http://jsfiddle.net/3aZZW/3/
Demo: http://jsfiddle.net/3aZZW/3/embedded/result/
There are different reasons why you should not use tables. Some which have already been discussed here. I understand that you are only using one row and you will hopefully try to keep your promise to not add any rows but if you come to break that promise, some of the reasons below will show a lot more significance, like the rendering speed and the screen reader issue. That's exactly why they call somethings standard and some not. Standards take everything and every situation into account.
Rendering speed issue:
One of the biggest drawbacks of tables is the way they are rendered by browsers. The inside of the table must be loaded before the position and size of the table can be exactly determined. This may cause problems if you are going to have a lot of information in the table.
Validness and standards:
Using tables for non-tabular data means you are writing invalid X/HTML. Which may be fine for some. But I don't recommend. See here
SEO:
I didn't know this before I did a search on some other less heard issues with using tables.
Search engines love valid code, so by not using tables it helps with
Search Engine Optimization (SEO).
See here for more info on this
Problems for screen readers and Braille displays:
Tables can't be used easily in screen readers. Check this article.
If you must use a table for layout, remember that screen readers and
Braille displays read tables row-by-row across the columns. The TAB
order also goes through the table in this way. So make sure that your
table structure makes sense when reading from left to right,
row-by-row.
On the + side:
I hate to admit that if you honestly use just that one table with one row and one column and with a very small amount of data inside (which I would call a limitation) then the page would probably render faster than the time you use Javascript but the other issues remain.
Tables are only meant to be used for tabular data - not for layout purposes.
Using tables for your problem provides a quick and easy solution for you but it doesn't mean it's the best, or correct method.
Just because something takes a little bit more thought and effort doesn't mean it should be avoided.
Use tables for this at your peril - your immortal soul may pay a heavy psychic toll at some future date for your actions today :p
According to StatCounter, as of November 2012, IE7 accounts for only 0.87% of the usage share of desktop browsers. It's not clear how accurate that measure is; some countries are probably disproportionately weighted and the sample-set almost certainly doesn't exactly match your user demographics, whatever they are. But, how much would you really lose by leaving IE7 behind? Might as well go with display: table;
On the other hand, it drives me nuts that display: table; is necessary. This is the closest I can get to a workable alternative:
HTML
<div id="pg-centerer">
<div id="shifter">
<div id="item">content</div>
</div>
</div>
CSS
#pg-centerer {
position: absolute;
left: 50%;
top: 50%;
}
#shifter {
position: relative;
height: 40px; /** Must set the height here. **/
left: -50%;
}
#item {
position: relative;
top: -50%;
}
So far, I haven't figured out how to avoid setting the height of the div#shifter element. Here's a working demo. I've tested this on Mac 10.8.1 FF 18, Safari 6.0, Chrome 25.0.1362.0 canary, and iOS Safari 6.0.1.
There is not much of a problem till you have small data inside table. Tables are somewhat heavy for browsers and with more data coming in, they make your web page response slower in comparison.
The example you have shown is only for an example but in real world you will have data inside it. If its going to be large try choosing a different method. may be the flexbox model or box model that is going to be supported in all modern browsers very soon. See an example here. http://www.kirupa.com/html5/centering_vertically_horizontally.htm
If the data inside is going to be small, feel free to user your method.
Directing my words to the geek inside who care not about standards, or multi-channeling content served... there is really just one technical problem with tables that I can think of, if you have large content inside that cell, the browser will wait for all content to load to be able to calculate the width and height of the cell before rendering... so if that content is really large and has large images, it will not render gradually... and making it a fixed table, well, the trick above won't work.
I depends on what you're trying to achieve. If it's just one page with one thing centered, then its great.
But I see you have set the table position: fixed. Which means it will scroll with you and go on top of content below. The other thing is that, if that table really fills up, you wont be able to see whats at the bottom of that table, since the position is set to fixed.
It's a great solution to center a small piece of text, image or information.
But its a bad thing to use within a page with a lot of other content or a lot of content within the table.
Side note: Using javascript to achieve something simple like that, is stupid. It can be done without javascript using CSS only. What if you use javascript to center something, and a client without javascript visits? Lets not destroy the web by using javascript/jquery for all the simple things ;)
http://phrogz.net/css/WhyTablesAreBadForLayout.html
Basically, it's slightly longer load times (JavaScript is slower), bad for screen readers (test it with one like JAWS), and hard to redesign (really only hard if you happen to forget why the heck you put a table there, so make sure to leave yourself a comment :). What would be really nice (I'm talking to you, W3C!) is something like box-align: x y;. Then you could also do things like align: center center or align: center bottom;.

How to access the screen size in html?

Is it possible?
You can do this with javascript using window.screen. See here.
no. but you can create layouts that depends not on pixels or cm, but percentages. they are called liquid layouts. also you can define a minimun width or height to be sure your layout won't broke in minnor screens.
other alternatives includes client side scripting (like javascript) as already said by the others.
Just in case you're asking to center something onto the screen/browser window:
Use CSS:
.cen {
margin: auto;
}
and in case it is a picture you want to center:
.cen {
position: absolute;
left: 50%;
top: 50%;
margin-left: -<witdh of image>/2;
margin-top: -<height of image>/2;
}
Another great way to do this is using #media queries.
A brief overview can be found here; http://www.css3.info/preview/media-queries/
Or a more thorough explanation from the W3C; http://www.w3.org/TR/css3-mediaqueries/
This may not be the best option if you're worried about a lack of support on older browsers, but if you're not, this is the best way to go!
Not in HTML, but in JavaScript.
window.screen has width and height properties.