I almost figured out what I need - see my answer, it's 90% complete
Background
I've finally transferred my website, as per a friends suggestion, from tables holding the images for the background to CSS.
When creating the original site (with tables), I couldn't get the page both horizontally centered and vertically. I used all the tags available, but it just wouldn't work. It was weird.
I got hold of JS to set content to the right place on the screen dependant on the window height and width, on onLoad() and onResize(). The Javascript was as follows:
function getWindowHeight() {
var windowHeight = 0;
if (typeof(window.innerHeight) == 'number') {
windowHeight = window.innerHeight;
}
else {
if (document.documentElement && document.documentElement.clientHeight) {
windowHeight = document.documentElement.clientHeight;
}
else {
if (document.body && document.body.clientHeight) {
windowHeight = document.body.clientHeight;
}
}
}
return windowHeight;
}
// Vertically center the #content div
function setContent()
{
if (document.getElementById) {
var windowHeight = getWindowHeight();
if (windowHeight > 0) {
var contentElement = document.getElementById('body');
var contentHeight = contentElement.offsetHeight;
var contentWidth = contentElement.offsetWidth;
if (windowHeight - contentHeight > 0) {
contentElement.style.position = 'relative';
contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
}
else {
contentElement.style.position = 'static';
}
}
}
}
Old to New
The original HTML uses tables to display everything. Very poor! So I've converted to CSS.
Here is the new page..
My Question
I need to center all my divs on the page, just like it was with tables. However, using the above JS in conjunction with align="center" places everything far too much to the right.
How do I center everything on screen so that when the screen is resized, it all stays in the center?
I have looked at containers, edited the Javascript above to account for .left and more. I need that tiny bit of code tailored to what I have. Can someone lend a quick hand, I've been at this for half a day. Thanks!
Basic code for what I want to center:
<body bgcolor="#a5a5a5" onLoad="setContent();" onResize="setContent();">
<div id="body" align="center">
<!-- Horizontal alignment handled with align tag, vertical via Javascript -->
<div id="img-01"><img src="images/img_01.jpg" width="12" height="584" alt="" align="center"></div>
<div id="img-02"><img src="images/img_02.jpg" width="365" height="17" alt="" align="center"></div>
// ... and more images in divs, up to about 23
How do I center all these? Just thought I'd note that originally it was a load of seperate div imgs, but I added the body div because it is referenced in the JS. When I had tables, it was just one div with all the table cells inside it, which is why it worked.
EDIT: When I DO think I have a horizontal center working, it seems more 75% to the right instead. Confused, please can someone help? :)
Your markup is a complete mess. It's using old, deprecated markup. It's missing a doctype. You are using absolute positioning throughout which is why you can't center it as you wish. You need to sit back and start from square one, learn what current modern practices are and build a very simple, one div version of this so you can get a handle on how things work today. What you show is totally unusable.
This may sound harsh but it is what it is. You are missing the basic fundamentals of web markup today.
Ok, your comment about adding as a background image got me thinking.....
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
body {
background-color:#a5a5a5;
background-image:url('Path to your one big image');
background-repeat:no-repeat;
background-attachment:fixed;
background-position:center;
}
</style>
</head>
<body>
</body>
</html>
Works in Chrome, IE 7-9, the latest Firefox and Safari. Image stays in the center of the page no matter how big the browser window is.
first throw a class on all those image divs
i'll call mine imageclass
body {width:100%;}
.imagediv {margin-left:auto;margin-right:auto;}
note: this will work if the images are wrapped inside a containter bigger than they are.
you could actually just use 1 css property here but i did it the long way.
edit- and actually you dont' really need the body {width:100%;}
that should be default and then yur wrapper should be set to 100%(inside of body)
Perhaps this link over at jsfiddle might help you get started. It is rough and doesn't have but half of your code but you get where it is going, I hope. Things to keep in mind:
1)the 'align=center' attribute has been deprecated for quite some time...this is a holdover from the days of tables.
2)You honestly don't need to use images to display your page how you want it. CSS supports box-shadows now and using google fonts or #font-face will get you the font you want right in your page (way better than using images. Search engines can read your text this way...this is a BIG factor in ranking well in Google Search, BTW).
3)Getting your container div to stay in the horizontal center is very easy, no matter how big your browser window is, using margin-left:auto and margin-right:auto set on your container div.
4)The vertical centering is a bit trickier, but you DON'T have to use Javascript! I suggest you search for 'vertically centering a div'.
The comments about your code being a mess, well, 10 years ago it would have been how you coded. Now, CSS makes things a LOT easier but you do need to take some time to learn it and about different browser quirks. Good luck with this and please post an update!
Related
I have a website that looks something like this:
http://illandril.net/outer.html
(Warning: AngularJS site on a server not setup to serve it properly - you'll need to go back to http://illandril.net/outer.html directly instead of using the browser reload.)
I seem to have two conflicting requirements though...
The images need to scale down when viewed on small screens (or in narrow browser windows)
There is a link that takes the user to the page already scrolled down to the "HEADER" section
My solution to #1 was simple...
img {
max-width: 100%;
}
But scrolling down to the HEADER area doesn't work, because the browser doesn't know how tall any of the images are (at least not on first view). "Easy", I thought... and I added width and height attributes to all my images.
Unfortunately, this made the images squished on narrow screens. So I adjust my CSS some more...
img {
max-width: 100%;
height: auto;
}
That fixed the squished image problem, but now the browser doesn't know how tall the images are again and scrolls to the wrong area when the page loads.
Is there some way I'm not aware of to tell the browser that images too wide to fit in their containers should be scaled down, but with a known aspect ratio so the image placeholders are all the right size before the image loads?
If it were a normal page, using window.onload for to trigger the scroll would work (See http://jsfiddle.net/nbS3F/1/), since that waits for all the images to load... but the site I'm working on is a single-page app using AngularJS, so the load event has long since fired by the time these new images are starting to load.
You must be doing the scrolling wrong. Use:
element.scrollIntoView(true);
With:
img {
max-width: 100%;
}
Fiddle
There is no such thing as "I want a max-width of 100%, but without a max-width of 100%".
I advise you to use css3 with responsive theme technique, you have to use different parameters in each screen size by applying :
#media only screen and
search google for responsive theme with jquery plug-in , this will help you a lot to design your website in professional way.
I've found a solution (though I'd prefer a nicer one still if anybody has one)... manually checking every single image to see if it is loaded or not, and listening to the onload and onerror events of the images not yet ready, scrolling only after all images have either loaded or failed.
var target = document.getElementById(targetID);
if (target) {
var scroll = function() {
target.scrollIntoView();
};
var toLoad = 0;
var onload = function() {
toLoad--;
if (toLoad === 0) {
scroll();
} else {
console.log('Waiting on ' + toLoad + ' images');
}
};
var images = document.querySelectorAll('img');
for (var i = 0; i < images.length; i++) {
if (!images[i].complete) {
toLoad++;
images[i].onload = onload;
images[i].onerror = onload;
}
}
if (toLoad === 0) {
scroll();
}
}
I'm designing a 2-column HTML5 interface (backwards compatibility is not important, all users will be using latest Chrome/FF), with a sidebar on the left and a main content area on the right.
I want the sidebar to have a background color as well as a right border (something like the OS X Finder sidebar). I want that background and border to extend to the bottom of the page, even if the page content isn't enough to extend the page to that size. I also want the sidebar to be set to a percentage, rather than a set amount of pixels.
Normally, I'd go with faux columns, or even liquid faux columns in this case. However I want to have a border to the right of the column, and I'm not sure if/how that's possible.
Ideally, I could do all this without images/faux columns at all. Is there a CSS3/HTML5 feature that will allow for that (as I said, backwards compatibility is not a problem)? If not, are there any other solutions to this besides making the sidebar a fixed size?
I think this demonstrates what you're looking for. If you have any questions about how this example works, don't hesitate to ask! :)
http://www.thechoppr.com/2009/02/09/2-column-fluid-layout-100-height-with-leftright-sidebar
Umm... that ?
<style type="text/css">
#left
{ height:100%;
width:25%;
min-width: 100px;
float:left;
background-color:red;
border-right:solid 3px orange;
}
</style>
<div id="left">menu</div>
<div id="right">contents</div>
You can use some jQuery:
var sidebar_height = 0;
var content_height = 0;
sidebar_height = $("#sidebar").height();
content_height = $("#content").height();
if(sidebar_height > content_height){
$("#content").css("height", sidebar_height);
} else {
$("#sidebar").css("height", content_height);
}
On my aspx page, I have two left and right portions. I want to show always left side (which is actually a 'div' containig treeview) while scrolling the right side (which are actual contents of page). Thanks
You need to put position: fixed; on the div element. That will anchor it to the viewport.
Hi I found the best solution! As always JQUERY saving my life !!
Just put a Div called as you wan, I've chosen the same in the example below: #scrollingDiv.
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script>
$().ready(function() {
var $scrollingDiv = $("#scrollingDiv");
$(window).scroll(function(){
$scrollingDiv
.stop()
.animate({"marginTop": ($(window).scrollTop() )}, "slow" );
});
});
</script>
I took that code from a website, it works and it's pretty easy to understand.
Fast forward to 2020, and it is now possible to do this with CSS.
<div style="position: sticky; top: 0;"> Tree view </div>
The user npas explains this quite nicely:
top is the distance to the viewport top the div should stay at when you scroll. Specifying top is mandatory. (…)
The sticky div will act like a normal div in all ways except when you scroll past it, then it will stick to the top of the browser.
Here's a jsfiddle to give you an idea.
MDN documentation
Supported by all modern browsers
You need to set the position of the div to Fixed in CSS. See this link for more information. You will need to set position using the top and left in css as well so it knows where to fix it!
The problem is that when the block moves, it gets attention and ability to concentrate on reading.
To remedy this using this function.
This code is perfect :
(change "220" and "46px" if necessary)
var $scrollingDiv = $("#scrollingDiv");
$(window).scroll(function(){
if ($(window).scrollTop()>220) {
$scrollingDiv
.css("position",'fixed' )
.css("top",'46px' )
} else {
$scrollingDiv
.css("position",'' )
.css("top",'' )
}
});
I'm doing some documentation where I make heavy use of anchors for linking between pages on a wiki.
see here:
http://code.google.com/p/xcmetadataservicestoolkit/wiki/ServicesExplained#Platform_Data_Structures
The feature that really makes this work well is when the browser shows the anchor at the absolute top of the pane. When it gets confusing is when linking to an anchor shows the anchor half-way down the page since the page is scrolled down all the way
see here:
http://code.google.com/p/xcmetadataservicestoolkit/source/browse/trunk/mst-common/src/java/xc/mst/utils/Util.java#227
My solution in the wiki (first link) was to put a blank image at the bottom of the page simply to make the browser show the anchor right at the top. Is there a better way to do this? Is there a way to do it in the second link (in which I can't add a blank image)?
Putting a blank image at the bottom of your page is a bad idea, since it will expand your document to a unnecessary height.
You could throw in some javascript to apply an effect to the anchor you just travelled to, to highlight it wherever it is.
Without altering the height of your document (i.e. adding extra padding at bottom), you'll always have this issue.
However, using bit of JS/jQuery, the user experience can be improved considerably:
On clicking a named anchor:
Instead of jumping in a flash (broswer's default behavior), add a smooth scroll
add an highlight to indicate current selection (this helps tremendously in 2nd case as the user can clearly see what is current)
Created a demo to illustrate the concepts: http://jsfiddle.net/mrchief/PYsyN/9/
CSS
<style>
.current { font-weight: bold; }
</style>
JS
function smoothScroll(elemId) {
// remove existing highlights
$('.current').css({backgroundColor: "transparent"}).removeClass('current');
var top = $(elemId).offset().top;
// do a smooth scroll
$('html, body').animate({scrollTop:top}, 500, function(){
// add an highlight
$(elemId).animate({backgroundColor: "#68BFEF" }, 500, function () {
// keep tab of current so that style can be reset later
$(elemId).addClass('current');
});
});
}
// when landing directly
if (document.location.hash) {
smoothScroll(document.location.hash);
}
$('a[href*="#"]').click(function() {
// utilizing the fact that named anchor has a corresponding id element
var elemId = $(this).attr('href');
smoothScroll(elemId);
});
You can create a absolutre positioned pseudo-element with a great height to targeted block using just the following CSS (for the second link in your post:
#nums td:target a::before {
content: '';
position: absolute;
height: 700px;
}
The height must be around the height of the viewport, so the best solution is to create these styles on the fly using js. But if you don't wan't to use js, just use height: 1000px or more — if you don't mind a gap at the bottom of course.
The best part: it's only CSS and there would be no gap when no anchors are targeted.
Edit: just a sneak peek into the future: if the vw/vh units would come to other browsers (now it's only in IE9), this could be awesomely done with just CSS using height: 100vh :)
You could use Javascript / jQuery to create a white div that has the necessary height needed to put your element at the top of the browser window, and you could even remove this upon scrolling away.
However I would highly recommend against doing so as this will expand your page where it isn't needed. It's a lot smarter to simply style the tag upon going there (through Javascript / jQuery) so it pops out to the viewer, for instance by setting the font-weight to bold or changing the background-color.
I would probably use a combination of jQuery and PHP for this:
PHP(somewhere right after your <body> element):
<?php
$anchor = explode('#', $_SERVER['REQUEST_URI']);
$anchor = $anchor[1];
echo '<div id="selected-anchor" anchor="'.$anchor.'"></div>';
?>
And then the jQuery:
<script type="text/javascript">
$(function(){
$('#selected-anchor').css('background-color', '[Whatever highlight color you want]');
});
</script>
Hope this helps.
I have to display a bunch of images in a page. Images are of different size, some very wide and some very thin. I want to put them all in a container of fixed width and fixed height.
Say if image is smaller, we retain the size and put it at the center of container. if image is bigger, we scale it down according to the prominent direction.
Our container is 500x500 and image is say 1000x400, then it will be scaled like 500x200. Similarly if image is 400x1000, then scaled image is 200x500. Is this doable with just html/css. Any help is appreciated. Thanks.
You can use max-width and max-height CSS properties to get the effect you want:
#container img {
max-width:500px;
max-height:500px:
}
Be aware that this does not work in IE6. To make it work there you may need to either scale the image serverside OR use expressions which are nasty. There are other workarounds which you can find on google :)
You'll get much better results if you resize the images on the server. Resizing in the browser means the client is downloading much larger files than necessary, and the resizing quality is not great.
No. It's not fully doable with htm and css.
img{ width: 100% }
will make 1000x400 image to appear as 500x200 bu 400x1000 will appear as 500x1200.
You can use javascrpt like:
function scaleimage(id)
{
var image = document.getElementById(id);
if(image.offsetWidth > image.offsetHeight)
{
if(image.offsetWidth > 500)
{
image.offsetHeight = image.offsetHeight * 500 / image.offsetWidth;
image.offsetWidth = 500;
}
}
else
{
if(image.offsetHeight > 500)
{
image.offsetWidth = image.offsetWidth * 500 / image.offsetHeiht;
image.offsetHeight = 500;
}
}
}
Sorry for poor formating, seems like my iPhone doesn't support it.
The best way to do it on the server. Or manually before uploading them (if it's possible).
You can use width and height CSS properties to get the effect you want:
container img {
width:500px;
height:500px:
}
Be aware that this work in all browsers.
Thanks
Ptiwari.