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;.
Related
Edit 3: I guess this is solved. I just enabled the Gutenberg editor and discovered its "Classic editor" part, the Code Editor. The only thing I have to get used to is the editor's line-height that I can't easily modify, which isn't bad. This is working for me and it outweighs the need to modify functions.php or other complicated things like that (to me). Thank you.
[Disclaimer: I'm not a developer of any sort, but willing to take the time. (Can do a bit of CSS.) Also, new to this forum.]
I’m using Anders Norén’s Hemingway theme.
I haven’t tried creating child themes yet and I’m not sure whether a solution to this requires one.
My goal, in short, is to make the whole “Edit Post” webpage look like an offline word processor:
Make the Visual editor occupy the whole screen. (I use the classic
editor.) (Done: Collapsed the vertical menu on the left side,
selected 1-column layout, and disabled “full height editor and
distraction-free functionality.”)
Set a width for the text (because currently text is almost from edge
to edge of screen)
Put text at the center (but “aligned left,” not “justified”). This
is for the "left and right margins," within the post editor.
How do I do #2 and #3?
Thank you.
Edit: Just to clarify: I'm looking to change how the Visual editor looks--only the Visual editor, not any output the live website would show.
Edit 2:
I can replicate what Balázs Varga showed, but (I'm sorry I should I have said this earlier) it doesn't work after I save the code on "Additional CSS." (And after clearing all caches.) I used the id #tinymce.
My browser (Firefox Developer) shows the changes in real time while I fiddle with the Inspector, but not after I save the additional CSS. That's weird, I think, and I think I can handle CSS pretty well: the theme Hemingway on my site doesn't look like the original Hemingway anymore, but all changes were made only through Additional CSS.
Searches on Google showed me that I might need to edit "functions.php"(?), but I don't know how that works for now, and I thought there might be another way in 2019. I avoid editing "complicated" things like that (to me), unless Wordpress makes it hard for me to break things, like with "Additional CSS," for example.
On the Inspector, I can solve it with something like this:
#tinymce {
margin-left: 300px;
margin-right: 300px;
}
I wonder why this isn't a "feature" of the Visual editor already. Would be really nice. It could eliminate the need for word processors or third party editors (at least for "words only" writers like me).
You can inspect the element in your browser, so you can see that it's a tinymce iframe with the id content_ifr.
If you want to set the width in pixels, you could do:
#content_ifr {
position: relative;
max-width: 600px;
left: 50%;
transform: translate(-50%, 0);
}
left:50% alongside with position:relative will push the element to the center horizontally. However it will push the left side to the center, so you also need a horizontal transform set to -50%, so it's pulled back to the correct position (because percents in transforms are counted from the size of the element itself, not from it's parent like left does)
You should see something like this:
If you want to set the width in percents, you can simply apply a margin-left to center the element:
#content_ifr {
width: 80%;
margin-left: 10%; // set this value to: (100 - width) / 2
}
EDIT
You can also edit your functions.php to append your styles to the page, for example in the header area with the admin_head hook:
function hook_css() {
?>
<style>
#content_ifr {
position: relative;
max-width: 600px;
left: 50%;
transform: translate(-50%, 0);
}
</style>
<?php
}
add_action('admin_head', 'hook_css');
can you please let me know if there is any chance to make that the label wraps itself and do not go like in the picture ("Change Change Change..."):
I use "no more tables" here and always get that issue with longer labels - they just do not wrap. I understand that the white-space in css is "nowrap", but if I change it to "normal", everything goes wrong and displays badly. Maybe someone had an issue with this "no more tables" technique and word-wrapping?
More about this script can be fuonde here http://elvery.net/demo/responsive-tables/
That example uses absolute positioning to move the generated content to the start of the rows and is a flawed approach as that means that the content cannot wrap because it will overlap the content in the next row. That's why the nowrap rule is in place to stop this happening.
Instead of absolute positioning you could use display:inline-block instead and avoid the issue altogether.
In the code from here change these two rules as follows:
td {
border: none;
border-bottom: 1px solid #eee;
position: relative;
}
td:before {
display:inline-block;
vertical-align:top;
width: 45%;
padding:0 3% 0 1%;
}
Rough example here:
Updated code as per comments below:
td:before {
float:left;
width: 95%;
padding:0 0 0 1%;
margin-left:-100%;
}
td {
padding-left:50%;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
box-sizing:border-box;
}
You need to break the words if they are too long. You can make this in css as:
word-wrap:break-word;
Try it.
The main issue here has to do with sizing one HTML element based on another element. This is something that tables are optimized to do - calculating the height and width of TD elements across the entire table to a uniform size dynamically based on content.
By abandoning tables (via changing the display type of THEAD to "block", effectively making it nothing more than a DIV), you've lost this automatic resizing effect that browsers do for you, as evidenced here:
There's no getting around this. The "No More Tables" approach must make a compromise - use absolute height to mimic the way tables are laid out. You are trying to reintroduce this automatic size calculation, but you can't without restructuring your HTML.
If you want to continue to pursue this path, you'd need to "manually" handle resizing of the TD elements - iterate over the cells of the table and resize them yourself whenever the size of table might have changed. While possible, your Javascript won't be nearly as optimized as the browser and anything you implement yourself will likely be buggy and slow.
I'm afraid the only viable solution is to shorten your label names and accept the need for absolute sizing to get around the lack of dynamic sizing in non-TABLE elements.
One possible solution: show an abbreviated label and then show a longer name in a popup on hover or tap: Tooltips for mobile browsers
Having seen advice seemingly change over the years regarding use of empty DIVs (ie. <DIV CLASS="somediv"></DIV>) I'm confused as to the current thinking over whether or not to use when a DIV will have no inner HTML.
I can find no definitive confirmation over whether we can rely on all modern browsers to display background color and image correctly at the specified width & height when there is no inner HTML, so I'm thinking maybe we can't rely on it - yet it's such a seemingly basic area.
I have even seen suggestions that empty DIVs should never be used - but do specs really state it is 'wrong' to have empty DIVs, or is it just unreliable? (I've tried finding reference to them, but maybe I'm using the wrong terms).
To illustrate, here are 5 areas where I would normally use an empty DIV, in the absence of any recommended alternative:
as a placeholder for content which will subsequently be fetched by XHR calls
as a way to manually create space in a layout
where an image is defined in CSS (as a background image, but will effectively be foreground)
where the text will come from the CSS using .somediv:after{content:SOMETEXT}
where CSS is used to display graph bars etc using solid background color
Maybe there are different answers for each of these, which might explain the complexity over this issue.
I have, of course, tried discovering already, but for example the SO question Is necessary to show an empty <div>? suggests to me there is a huge amount of "IMHO", "probably", "seems to work" in this area. I would expect that by now that some official consensus has been reached on best practice.
So.. should I use and if so should I set font-size to the same as the smaller of DIV width/height to ensure that space is filled in all browsers? Are there any other CSS tricks to ensure this will work in all browsers?
The browser is not going to discard or forget your container just because it does not have any contents (yet).
If you want the container to have a specific placeholder shape, then you might give it min-height, min-width, height and width and make sure it's display: block;.
If you are still unsure, you can fill it with a spacer.gif/png without padding and margin.
http://jsfiddle.net/APxNF/1/
Short answer. Yes, browsers will render the div even if there is no content.
Long answer, That might now always be the case. I have worked in the web for 8 years now and never had to use these, but here they are anyway.
jsFiddle demo
HTML
<div class="empty1"></div>
<div class="empty2"></div>
<div class="empty3"></div>
CSS
.empty1 {
background: #FBB829;
height: 100px;
width: 100px;
}
.empty2:before {
content: "\00a0";
}
.empty2 {
background: #FF0066;
height: 100px;
width: 100px;
}
.empty3 {
background: #F02311;
min-height: 1px;
height: 100px;
width: 100px;
}
Sources:
Experience
Empty div with 2px width and background color doesnt show with height as 100%
http://csscreator.com/node/36023
Hi all and thanks in advance for your help.
I'm pretty new to the CSS, and I would like to have a good input to start building and learning the fastest way possible. I'm already doing some CSS tests myself. Right on the question.
this is the relative css code (I put it on pastebin because it's a bit long)
CSS CODE
As you can see in the code, the 2 tables showing up in the image, have a background and I had to set their size manually with
width:100px;
height:120px;
in the td.menuleft and td.menucenter classes.
1° Question
How do I make automatically resizing cells?
For example i want to say:
Make table tag wide 100% of the page width, then let me make classes for cell tables that are a certain percentage of the table width.
Example
Pic of my work, and how I want to make it like
This way it will be easy to make up tables into tags to automatically fill pages. I've seen something about positioning (relative, absolute) but I didn't managed to make it work.
2° question
What's the best way to structure a web page with css in general? It's ok to do like I said, a div, with tables inside and place every element in a table like manner?
Or can you give me any guide step to step on how to do a particular template?
Thanks guys.
when you want to learn how to make good and effective design that are also considered any worth by search engines, then don't use tables for layouts. tables are there for showing table data, not layout. Use instead divs and start reading about positions, displays, floats.
That is the way you want to go
If you set the tds to be a certain percentage width, they will be the percentage of the parent. so:
table {
width: 100px;
}
tr {
width: 100% /* Will be 100px */
}
td.quarter {
width: 25%; /* Will be 25px */
}
td.half {
width: 50%; /* Will be 50px */
}
And I agree with the previous poster, do NOT use tables for layouts. Not that you are doing that here. But for layouts stick to divs and such.
I have a two column layout, with a gray sidebar on the right. I need the sidebar's height to expand when the height of the left column is increased (due to content being dynamically expanded). I can make the sidebar fit a static page, but I cannot get it to increase in size with the rest of the page. Did some Googling, but couldn't find a work-around that worked for me.
Does anyone know how to do this?
This is a common problem when using DIVS for this type of layout.
If you google 'Faux column' you should get some answers.
eg. http://www.alistapart.com/articles/fauxcolumns/
This may be slightly off but if you use jQuery on your site you can perform a quick calculation and resize all DIVs sharing a similar class to the maximum height:
$('.elements').height(Math.max($('#div1').height(), $('#div2').height()));
I have been haunted by this problem for a while and I wrote an article about this issue: Done with faux columns. Here is what I argued:
JavaScript based solution for this
problem is not worse than any other
solution. In fact if you are using
JavaScript, you may save a few hours
of frustration of trying to get things
working. People will warn you against
this by saying “What will happen if
the user turned off JavaScript?“.
Believe me, if the user has turned off
JavaScript, most of the web is broken
for him anyway. Your sidebar does not
matter to him.
As cballou mentioned, the simplest way to do this thing is to use JQuery code:
$(".sidebar").height(Math.max($(".content").height(),$(".sidebar").height()));
I changed the background-color to the same color as my sidebar, on that specific page, although I do have backgrounds for all my sections rather than one overall background. But that might not work for everyone.
In my stylesheet,
.sidec
{
background-color:#123456;
}
In my HTML page,
<body class="sidec">
content....
</body>
I recently saw a quite creative solution to this problem using the CSS properties position:absolute and border.
Definitely worth checking out to see if it works for you.
Link: http://woorkup.com/2009/10/11/really-simple-css-trick-for-equal-height-columns/
I'm not sure if this will help, as I'm a newbie. However, when struggling with getting my sidebar to show the whole content when I doubled it's size I did the following. I was changing my height and width with no response until I changed the class. My class was listed SB frame SB width. So when I changed my class to read SB height SB width it fit to my content instead of the original frame size. I also tried SB max sb width with worked too, but it took out my footer menu bar (meaning it wouldn't show it anymore). I went back to SB height SB width, and all is well. That's super duper elementary for all of you I'm sure, but just in case there is another newbie reading this that doesn't understand much about html code like myself... I hope this helps =)
Happy Holidays Everyone!
hugs, tara
I'm guessing you want to apply certain effect to your layout such that it will require both columns to resize together. If you want to dynamically change the values of the height of the columns, I doubt it will work simply with css unless you implement some javascript to control the style.
As Dal suggested, do look at the link on faux columns. As the name suggests, the solution isn't much about modifying the columns height. Instead, it gives the "illusion" that both columns appear to be of the same height when in reality they are not -- and is with the use of tiles of background image.
The idea is there isn't a need to complicate the mark-up. Simple structure with a touch of "illusion" with images is a common practice in web design.
Regards,
Jonah
With the poor attitude towards new members on here I expect to be barracked for this answer, here goes.
I got around this problem by creating a background image 960px wide 1px high with the two colors I needed for the columns in their respective widths (780px and 180px). I then used this as the background image for my container repeated on the y axis and made the content and the right sidebar background-color: transparent.
.container {
width: 960px;
background-color: #FFFFFF;
margin: 0 auto;
background-image: url(../images/bgs/conbg.jpg);
background-repeat: repeat-y;
}
.sidebar1 {
float: right;
width: 180px;
height:auto;
background-color:transparent;
padding-bottom: 10px;
}
.content {
padding: 10px 0;
width: 780px;
background-color:transparent;
float: right;
}
I am sure that this method has its limitations but it works perfectly on all my pages.
It is possible that I have not explained this very well, if so, be nice about it will you please. I will endevour to expand on my method(which is probably already common knowledge).