Full Width images with minimal CSS - css

I am (was) looking for a way that my images would be full width despite the body padding. And, I wanted my images to also not be too tall.
Making matters more difficult, (a) all of the images live inside of <p> tags and I can't (easily) assign classes, etc to them. That is because the pages are generated from a Markdown conversion and I wanted to avoid having to apply a ton of regex (though I was willing to if need be).
The requirements were basically that the text be padded inside the body (but not via a p margin so I didn't have to deal with non-paragraph elements). And, I wanted it such that the maximum height was some percentage of the current width. Finally, in addition to trying to avoid touching the HTML, I also didn't want to add any js if I could help it.

The following is my solution. It still needs some tinkering since you can become height-constrained before width-constrained with square images but if nothing else it is a start. Again, this may be super obvious to those more experienced.
Define the folliwng
$pad to be the padding of the body (2em)
$body_width to be the width of the body element (900px
$mh is the fraction to set the max height. Again, this is personal preference for the type of images you care about. I'll do 0.9 in this example.
body {
margin: 1em auto auto;
max-width: 900px; /* $body_width */
padding: 0.1em 2em 2em; /* $pad $pad */
}
video,img{
border: 0;
max-width: calc(100% + 4em); /* + 2*$pad */
max-height: 810px; /* $mh * $body_width
display: block;
/* From [1] */
position: relative;
left: 50%;
transform: translateX(-50%);
display: block;
}
[reference 1]
But I also wanted to handle tall screens with width less than max (i.e. mobile).
#media only screen and (max-width : 900px) { /* $mh*$body_width */
img,video {
max-height: 100vw;
}
}
It works by first making the image max width go beyond the padding and then using transform to center it.
I hope this helps someone in the future. It could have saved me a day!

Related

Perfectly responsive float box loses bottom margin in mobile view

I put together a page that has a .floatbox, which sets the top and bottom margin based on the variable --currentViewportHeight (basically, I dynamically detect it with JS and insert it into my CSS, on page load and resize); --autoTopBottomMargin is set arbitrarily to 0.1 because this is how big I want the top and bottom margins to be. The following class allows me to have very nice, dynamic top and bottom margins.
.floatbox {
position: relative;
width: 500px;
left: 50%;
transform: translate(-50%);
margin-top: calc(var(--currentViewportHeight) * 1px * var(--autoTopBottomMargin));
margin-bottom: calc(var(--currentViewportHeight) * 1px * var(--autoTopBottomMargin));
padding-top: 20px;
}
Then, when the size of the viewport becomes less than the the size of .floatbox (with a little wiggle room—600px, to be precise), I go into the responsive spec. 0.00176 determines the perfect relative size and right-hand margin in one go.
#media only screen and (max-width: 600px) {
.floatbox {
position: absolute;
transform-origin: left top;
transform: scale(calc(var(--currentViewportWidth) * 0.00176));
top: calc(var(--currentViewportWidth) * 1px * var(--repositionFactor));
left: calc(var(--currentViewportWidth) * 1px * var(--repositionFactor));
margin-top: unset;
}
}
Here, I use --currentViewportWidth (also detected with JS and inserted dynamically into my CSS) to perfectly scale .floatbox, so it's sized exactly right and with the exactly right margins on any device.
Seemingly, everything is just fine...except, no matter what I do, I cannot set margin-bottom for the responsive spec, by using either static or dynamic values. On mobile, it just sticks to the bottom of the screen.
I figure that I must be missing something really obvious here...

Make box responsive in CSS

I am trying to make the box responsive to scale with the mobile but it turns out it is very small when I resize the window.
Here is the HTML code:
<div class="box">
<h1>Health Status</h1>
<input type="text" id="check_infected" name="infected_check" placeholder="Infected by Corona? (Yes/No)">
<input type="submit" onclick="UpdateHealth();" value="Update">
<div class="bottom-text">
We ensure to secure your health as well as the public health
</div>
Here is the CSS code:
.box{
width: 30%;
padding-top: 30px;
padding-bottom: 30px;
padding-left: 100px;
padding-right: 100px;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background: #ffffff;
text-align: center;
}
#media only screen and (min-width: 375px) and (max-width: 812px) {
.box{
padding-top: 60px;
padding-bottom: 60px;
}
}
This is the image when it is not resized:
It turns out very small when it is resized:
How can I make the box scale with the screen or at least make the responsive box easier to see?
preliminary version: this anwser will need some updating depending on OP/any comment, so, please comment on errors, inconsistencies and omissions.
Intro
While the question is easy enough, 'how to scale a box to fit any device?', quite a few considerations need to be made. Instead of summing them up, I will use the images and code OP posted and take those to show how I came to my final version of the box (by approximation).
In any case, I will not be using several Media Queries when a single equation in a CSS calc(), can do the job just fine. Over the past few years I have learned to use a single equation (Codepen: responsive typography, CSS-Tricks: Simplified Fluid Typography and Typekit blog: Flexible typography with CSS locks, to name a few examples) to calculate any CSS size-attribute value for any given browser viewport size, instead of using a list of MQs testing for specific viewport sizes ('breakpoints') and set specific size-attribute values.
The math is rather straighforward, linear equation: y=mx+b, which uses two known points on a straight line to calculate all other points on that line (check out MathIsFun: Equation of a Straight Line, easy to understand Middle School explanations, well worth the read).
Pro: Short code and works for any CSS size-attribute that accepts CSS calc(). Results in (much) less CSS, less maintenance.
Con: May take some more preparation when coding and only works for straight lines (no rocket science included) and exceptions to the CSS calc() result may still need some Media Query.
tl;dr - It is quite a lot of text, so here's the snippet first:
/*
All sizes in REM to honour browser user font settings (REM = size/16)
*/
.box {
/*
Going for approach 1. (Stackoverflow 61980111) to create the final box,
we only need to define some smart padding.
T/B (320,60)(1760, 30), y=-2.08vmin + 66.67
L/R (320,30)(1760,100), y=4.87x + 14.45
*/
padding: calc(-2.08vmin + 4.167rem) calc(4.87vmin + 0.9rem);
}
/* (320,14)(1280,20), y=0.00625x + 12 */
html { font-size: calc(0.625vmin + 0.75rem) }
body { font-size: 1rem }
input { font-size: 0.875rem; text-align: center }
/* (320,18)(1920,28), y=0.00625x + 16 */
h1 { font-size: calc(0.625vmin + 1rem); font-weight: normal }
/* Flexbox layout */
.wrapper, .box { display: flex; flex-direction: column; justify-content: center; align-items: center }
.wrapper { height: 100% }
/**************************************/
/* Generally accepted preferred rules */
/**************************************/
html,body { box-sizing: border-box; width: 100%; max-width: 100%; height: 100% }
*::before,*::after, * { box-sizing: inherit }
body { margin: 0 }
/******************/
/* eye-candy only */
/******************/
body {
color: rgba(0,0,0,.7);
background-image: linear-gradient(330deg, #e94974, #8073ab)
}
#media (orientation: portrait ) and (min-width : 50rem),
(orientation: landscape) and (min-height: 50rem) {
body { background-image: linear-gradient(330deg, #3f96c8, #23c1bc) }
}
.box {
background-color: white;
text-align: center;
/* GMC elevation 3dp */
box-shadow: 0px 3px 3px -2px rgba(0,0,0,.20),
0px 3px 4px 0px rgba(0,0,0,.14),
0px 1px 8px 0px rgba(0,0,0,.12);
}
input { margin-bottom: 1.5rem }
.pill {
box-sizing: border-box;
position: relative; overflow: hidden; cursor: pointer;
/* Flexbox Layout */
display: inline-flex;
justify-content: center;
align-content : center;
align-items : center;
/* Override default styling */
padding: 0; border: none; outline: none; text-decoration: none;
/* Sizing */
width : 70%;
height: calc(0.75vmin + 2.85rem); /* (320,48)(1920,60), y=0.75x + 45.6 */
line-height: calc(0.75vmin + 2.85rem);
/* Styling */
opacity: .85;
background-color: transparent; color: currentColor;
border: 2px solid #ee7752;
border-radius: calc((0.75vmin + 2.85rem)/2);
/* IE has a problem with this and won't show rounded border, well known quirk! */
/* Content not selectable */
-webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none;
-moz-appearance: none; -webkit-appearance: none;
}
.pill:hover { opacity: 1 }
/* override default pill border color */
input[type="submit"].pill { border-color: #23a6d5 }
/* simulates button 'press' behaviour */
input[type="submit"]:active { transform: scale(.99) }
<div class="wrapper">
<div class="box">
<h1>HEALTH STATUS</h1>
<input class="pill" type="text" id="check_infected" name="infected_check"
placeholder="Infected by Corona? (Yes/No)"
onfocus="this.placeholder = ''"
onblur="this.placeholder = 'Infected by Corona? (Yes/No)'">
<input class="pill" type="submit" onclick="UpdateHealth();" value="Update">
<p class="bottom-text">We ensure to secure your health as well as the public health</p>
</div>
</div>
So, what do we know? (derived from OP posted images and code)
viewport: 861x1883 (blue image size), ratio 2.18699
box: 505x877 (measured in image)
height 58.66% and width 46.58% in landscape mode (OP defined width: 30%)
ratio 1883/861 ~ 1.736633, close to either 17:10 (1.7) or 16:9 (1.78)
or stick to 1.736633
padding: 30px 100px, large devices (defined in CSS)
padding: 30px 60px, small devices (between 375px and 812px)
We cannot simply use a single percentage for box W/H and padding because of the different height/width ratios of mobiles vs tablets vs desktops.
Mobile OS'es have their own style of presenting modals:
floating on top of the main app with some (narrow) margin
or they go full screen
Are we going to mimic mobile behaviour or define our own style?
Check statcounter to get background info on current device resolutions to determine possible W/H and ratio for our box:
mobile (1.78 or 2.16, 360x640, 414x896)
tablet (1.3 or 1.6, 768x1024, 800x1280)
desktop (1.78, 1366x768, 1920x1080)
Approaches
There are various approaches to create the box the OP requires (in order of complexity, least complex first):
Let the content determine the size of the box. The more content, the taller the box grows. In this case we basically don't know the final size of the box and will need to create some (responsive) inner spacing taking the original height/width ratio into account.
=> box itself will not overflow (just grow), parent element might, depending on box content.
Let the box's parent element (body or some wrapper) determine the size of the box. This means that we need to manipulate the parent element inner space to create room for the box, as well as define some responsive inner box spacing.
=> either/neither box or parent may overflow depending on box content and overflow settings.
Create a responsive sizing box by manipulating its height, width and inner spacing. While the box size itself is responsive, its width and height are limited by the equation result. As with 2., some responsive inner box spacing has to be defined.
=> depending on content and spacing the box might overflow.
Given the layout, content and requirements by OP we will be using approach 1. For easy positioning of the box inside the viewport, as well as its content we will be using CSS 'flexbox layout'.
Check out CSS-tricks A Complete Guide to Flexbox for a reference on FBL.
The MATH
using linear equation y=mx+b
Envision an XY-graph with two points and a line drawn through those points, where
x-axis = viewport size in px (either width or height of the browser window, parent element, device, etc.)
y-axis = size-attribute value in px (any CSS attribute that accepts the use of CSS calc(), like font-size, width, height, padding, margin, top, left, bottom, right, etc.)
Those two points, p1(x1,y1) and p2(x2,y2), depict a small size-attribute value on a small device and a large size-attribute value on a large device.
x1 = minimum viewport size (mobile), y1 = minimum size-attribute value
x2 = maximum viewport size (desktop), y2 = maximum size-attribute value
For example, in the snippet the equation for html { font-size: calc(0.625vmin + 0.75rem) } is derived by using points p1(320,14) and p2(1280,20),
actually meaning: p1 = 'minimum fontsize of 14px on a 320px screen' and p2 = 'maximum fontsize of 20px on a 1280px screen'.
In this instance, we use p1 and p2 to calculate the box inner space (padding) by using either linear equation:
for CSS calc()
Y-intercept form: y = mx + b
CSS size-attribute: calc(m * x + b)
where
m = (y2 - y1) / (x2 - x1)
x = is always 100vmin/vh/vw/vmax, depends on size-attribute viewport W/H (in)dependency
b = y1 - m * x1
alternatively use
point slope form: y = y1 + m(x - x1)
CSS size-attribute: calc(y1 * 1px + (y2 - y1) / (x2 - x1) * (x - x1 * 1px)), with 'm' substituted and using '* 1px' to convert to pixel units, otherwise CSS calc() will fail.
(Whichever fits your needs, where probably best is to manually calculate Y-INTERCEPT FORM variables 'm' and 'b' for use in calc(), less CPU intensive. POINT SLOPE FORM is great for use with CSS variables, SCSS and JS.)
Notes
for any CSS calc() used in the snippet, values for points p1 and p2 and the resulting equation are shown in /* comments */
Set limits/constraints by using media queries. In case of element width and/or height attributes you can set their min-/max- counterparts.
Use flexbox layout to center the box in the viewport.
If you don't want to go full screen and use approach 3., determine a H:W ratio for any given device (best done in JS instead of #media), depends on device orientation. Using device ratios for you box makes the end result look better on a device.
Make sure you 'own' this math, the sooner the better. With a few cleverly chosen minimums, maximums and simple calculations you can solve many responsiveness issues where you would otherwise need (vast) lists of Media Queries to accomplish the same result.
Please do pass the word as I think there are way too little developers using this technique for responsive design.
Short answer: your image width is 30% in your CSS code. When your screen is 1000px the image is normal with 300px but when you use a mobile phone with 320px screen the image is only 96px.
In your media query, you are only defining a different padding-top and padding-bottom, but the rest of the settings stay the same as in the general CSS rule (for example width: 30%, which is probably the main problem).
You need to include and change every setting which you want to change in the media query, especially width and the paddings, similar to this:
#media only screen and (min-width: 375px) and (max-width: 812px) {
.box{
box-sizing: border-box;
width: 80%;
padding-left: 10%
padding-right: 10%;
padding-top: 60px;
padding-bottom: 60px;
}
}

Can we define min-margin and max-margin, max-padding and min-padding in css?

Can we define min-margin and max-margin, max-padding and min-padding in CSS ?
Yes, you can!
Or if not those terms exactly, then at least the next best thing. In 2020 this is now very straightforward using the CSS math functions: min(), max(), and clamp().
A min calculation picks the smallest from a comma separated list of values (of any length). This can be used to define a max-padding or max-margin rule:
padding-right: min(50px, 5%);
A max calculation similarly picks the largest from a comma separated list of values (of any length). This can be used to define a min-padding or min-margin rule:
padding-right: max(15px, 5%);
A clamp takes three values; the minimum, preferred, and maximum values, in that order.
padding-right: clamp(15px, 5%, 50px);
MDN specifies that clamp is actually just shorthand for:
max(MINIMUM, min(PREFERRED, MAXIMUM))
Here is a clamp being used to contain a 25vw margin between the values 100px and 200px:
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.container {
width: 100vw;
border: 2px dashed red;
}
.margin {
width: auto;
min-width: min-content;
background-color: lightblue;
padding: 10px;
margin-right: clamp(100px, 25vw, 200px);
}
<div class="container">
<div class="margin">
The margin-right on this div uses 25vw as its preferred value,
100px as its minimum, and 200px as its maximum.
</div>
</div>
The math functions can be used in all sorts of different scenarios, even potentially obscure ones like scaling font-size - they are not just for controlling margin and padding. Check out the full list of use cases at the MDN links at the top of this post.
Here is the caniuse list of browser support. Coverage is generally very good, including almost all modern browsers - with the exception, it appears, of some secondary mobile browsers although have not tested this myself.
UPDATE 2020
With the new (yet in Editor's draft) CSS 4 properties you can achieve this by using min() and max() (also you can use clamp() as a - kind of - shorthand for both min() and max()
clamp(MIN, VAL, MAX) is resolved as max(MIN, min(VAL, MAX))
min() syntax:
min( <calc-sum># )
where
<calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]*
where
<calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]*
where
<calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )
max() syntax:
max( <calc-sum># )
where
<calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]*
where
<calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]*
where
<calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )
clamp() syntax:
clamp( <calc-sum>#{3} )
where
<calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]*
where
<calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]*
where
<calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )
Snippet
.min {
/* demo */
border: green dashed 5px;
/*this your min padding-left*/
padding-left: min(50vw, 50px);
}
.max {
/* demo */
border: blue solid 5px;
/*this your max padding-left*/
padding-left: max(50vw, 500px);
}
.clamp {
/* demo */
border: red dotted 5px;
/*this your clamp padding-left*/
padding-left: clamp(50vw, 70vw, 1000px);
}
/* demo */
* {
box-sizing: border-box
}
section {
width: 50vw;
}
div {
height: 100px
}
/* end of demo */
<section>
<div class="min"></div>
<div class="max"></div>
<div class="clamp"></div>
</section>
Old Answer
No you can't.
margin and padding properties don't have the min/max prefixes
An approximately way would be using relative units (vh/vw), but still not min/max
And as #vigilante_stark pointed out in the answer, the CSS calc() function could be another workaround, something like these:
/* demo */
* {
box-sizing: border-box
}
section {
background-color: red;
width: 50vw;
height: 50px;
position: relative;
}
div {
width: inherit;
height: inherit;
position: absolute;
top: 0;
left: 0
}
/* end of demo */
.min {
/* demo */
border: green dashed 4px;
/*this your min padding-left*/
padding-left: calc(50vw + 50px);
}
.max {
/* demo */
border: blue solid 3px;
/*this your max padding-left*/
padding-left: calc(50vw + 200px);
}
<section>
<div class="min"></div>
<div class="max"></div>
</section>
I was faced with the same problem today. Apparently the solution is as simple as using :
padding: calc(*put fixed pixels here*px + *put your required %age here*%)
Note that you do have to decrement the required %age a little to account for fixed pixels.
Unfortunately you cannot.
I tried using the CSS max function in padding to attempt this functionality, but I got a parse error in my css. Below is what I tried:
padding: 5px max(50vw - 350px, 10vw);
I then tried to separate the operations into variables, and that didn't work either
--padding: calc(50vw - 350px);
--max-padding: max(1vw, var(--padding));
padding: 5px var(--max-padding);
What eventually worked was just nesting what I wanted padded in a div with class "centered" and using max width and width like so
.centered {
width: 98vw;
max-width: 700px;
height: 100%;
margin: 0 auto;
}
Unfortunately, this appears to be the best way to mimic a "max-padding" and "min-padding". I imagine the technique would be similar for "min-margin" and "max-margin". Hopefully this gets added at some point!
margin and padding don't have min or max prefixes. Sometimes you can try to specify margin and padding in terms of percentage to make it variable with respect to screen size.
Further you can also use min-width, max-width, min-height and max-height for doing the similar things.
Hope it helps.
You can also use #media queries to establish your max/min padding/margin (but only according to screen size):
Let's say you want a max padding of 8px, you can do the following
div {
padding: 1vh 0;
}
#media (max-height: 800px) {
div {
padding: 8px 0;
}
}
I think I just ran into a similar issue where I was trying to center a login box (like the gmail login box). When resizing the window, the center box would overflow out of the browser window (top) as soon as the browser window became smaller than the box. Because of this, in a small window, even when scrolling up, the top content was lost.
I was able to fix this by replacing the centering method I used by the "margin: auto" way of centering the box in its container. This prevents the box from overflowing in my case, keeping all content available. (minimum margin seems to be 0).
Good Luck !
edit: margin: auto only works to vertically center something if the parent element has its display property set to "flex".
Late to the party, but I'd like to share my simple solution.
I'm gonna assume that if we want something that would work like a min-margin, it's because we have a margin: auto; in the first place, and we don't want that margin auto being smaller than a certain number.
We can do that with two div, one inside another.
Here is an example with horizontal margins.
<div class="margin-auto">
<div class="min-margin">
<p>Lorem Ipsum etc</p>
</div>
</div>
As for the css:
.margin-auto {
margin: 0 auto;
}
.min-margin {
margin: 0 16px;
max-width: 300px;
}
I ran across this looking for a way to do a max-margin for responsive design. I need a 5% margin for mobile/tablet devices up to 48 pixels wide. Berd gave me the answer by using media queries.
My answer:
48 * 2 = 96 total max margin
96 is 10% of total width.
10 * 96 = (960) 100% of vw where 48px is the first time I want it to overwrite the % .
So my media queries to control my margins become:
#media (max-width: 959px) {
.content {
margin: 30px 5% 48px;
}
}
#media (min-width: 960px) {
.content {
display:block;
margin: 30px 48px 48px;
}
}
var w = window.innerWidth;
var h = window.innerHeight;
if(w < 1116)
document.getElementById("profile").style.margin = "25px 0px 0px 975px";
else
document.getElementById("profile").style.margin = "25px 0px 0px 89%";
Use code above as an example of how to set min-margin and padding
Ideally, margins in CSS containers should collapse, so you can define a parent container which sets its margins(s) to the minimum you want, and then use the margin(s) you want for the child, and the content of the child will use the larger margins between the parent and child margin:
if the child margin(s) are smaller than the parent margin(s)+its padding(s), then the child margins(s) will have no effect.
if the child margin(s) are larger than the parent margin(s)+its padding(s), then the parent padding(s) should be increased to fit.
This is still frequently not working as intended in CSS: currently CSS allows margin(s) of a child to collapse into the margin(s) of the parent (extending them if necesary), only if the parent defines NO padding and NO border and no intermediate sibling content exist in the parent between the child and the begining of the content box of the parent; however there may be floatting or positioned sibling elements, which are ignored for computing margins, unless they use "clear:" to also extend the parent's content-box and compltely fit their own content vertically in it (only the parent's height of the content-box is increased for the top-to-bottom or bottom-to-top block-direction of its content box, or only the parent's width for the left-to-right or right-to-left block-direction; the inline-direction of the parent's content-box plays no role) .
So if the parent defines only 1px of padding, or only 1px of border, then this stops the child from collapsing its margin into the parent's margin. Instead the child margins will take effect from the content box of the parent (or the border box of the intermediate sibling content if there's any one). This means that any non-null border or non-null padding in the parent is treated by the child as if this was a sibling content in the same parent.
So this simple solution should work: use an additional parent without any border or padding to set the minimum margin to nest the child element in it; you can still add borders or paddings to the child (if needed) where you'll defining its own secondary margin (collapsing into the parent(s) margins) !
Note that a child element may collapse its margin(s) into several levels of parents ! This means that you can define several minimums (e.g. for the minimum between 3 values, use two levels of parents to contain the child).
Sometimes 3 or more values are needed to account for: the viewport width, the document width, the section container width, the presence or absence of external floats stealing space in the container, and the minimum width needed for the child content itself. All these widths may be variable and may depend as well on the kind of browser used (including its accessibility settings, such as text zoom, or "Hi-DPI" adjustments of sizes in renderers depending on capabilities of the target viewing device, or sometimes because there's a user-tunable choice of layouts such as personal "skins" or other user's preferences, or the set of available fonts on the final rendering host, which means that exact font sizes are hard to predict safely, to match exact sizes in "pixels" for images or borders ; as well users have a wide variety of screen sizes or paper sizes if printing, and orientations ; scrolling is also not even available or possible to compensate, and truncation of overflowing contents is most often undesirable; as well using excessive "clears" is wasting space and makes the rendered document much less accessible).
We need to save space, without packing too much info and keeping clarity fore readers, and ease of navigation : a layout is a constant tradeoff, between saving space and showing more information at once to avoid additional scrolling or navigation to other pages, and keeping the packed info displayed easy to navigate or interact with).
But HTML is often not enough flexible for all goals, and even if it offers some advanced features, they becomes difficult to author or to maintain/change the documents (or the infos they contain), or readapt the content later for other goals or presentations. Keeping things simple avoids this issue and if we use these simple tricks that have nearly no cost and are easy to understand, we should use them (this will always save lot of precious time, including for web designers).
Comming late to the party, as said above there unfortunately is no such thing as max-margin. A sollution that helped me is to place a div above the item you want to have the max-margin applied to.
<body style="width:90vw; height:90vh;">
<div name="parrentdiv/body" style="width:300px; height:100%; background-color: blue">
<div name="margin top" style="width:300px; height:50%; min-height:200px; background-color: red"></div>
<div name="item" style="width:300px; height:180px; background-color: lightgrey">Hello World!</div>
</div>
</body>
Run above coded snippet in full page and resize the window to see this working. The lightgreypart will have the margin-top of 50% and a 'min-margin-top' of 200px. This margin is the red div (wich you can hide with display: none; if you want to). The blue part is what's left of the body.
I hope this will help people with the same problem in the future.
#vigilante_stark's answer worked for me. It can be used to set a minimum "approximately" fixed margin in pixels. But in a responsive layout, when the width of the page is increasing margin can be increased by a percentage according to the given percentage as well.
I used it as follows
example-class{
margin: 0 calc(20px + 5%) 0 0;
}
This seems to work for me to make a responsive iframe embed with a max height set.
.embed-container {
position: relative;
padding-bottom: min(80vh, 100%);
width: 100%;
height: 100%;
max-height: 80vh;
overflow: hidden;
max-width: 100%;
}
.embed-container iframe,
.embed-container object,
.embed-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
max-height: 80vh;
}
<div class="embed-container">
<iframe
src="https://player.vimeo.com/video/405184815?title=0&byline=0&portrait=0"
frameborder="0"
webkitAllowFullScreen
mozallowfullscreen
allowfullscreen
></iframe>
I was looking for a solution to make the contents of a row behave like in a fixed width container, but with shrinking browser width make a minimal margin from the left (in my case: so that the row contents do not hide under a big logo with position: absolute in left-top).
This is what worked for me:
HTML
<div class="parent-container">
<div class="child-container">
<h1>Some header</h1>
</div>
</div>
CSS
.parent-container {
padding-left: min(150px);
}
.child-container {
padding-left: calc( 50vw - 500px );
}
When I scale the browser window left and right, my h1 doesn't go to the left more than the 150px, but goes right following the behavior of my next row's content set to display in a fixed container.
See this CodePen https://codepen.io/ella301/pen/vYLNmVg which I created. I used 3 CSS functions min, max and calc to make sure the left and right paddings are fluid between minimum 20px and maximum 120px.
padding: 20px max(min(120px, calc((100% - 1198px) / 2)), 20px);
Hope it helps!
I wrote a library to do this, you can view it here: https://codepen.io/nicetransition/pen/OyRwKq
to use in your case:
.selector {
scale($context, $base-size, $limit-size-min, $limit-size-max, $property: padding-right);
scale($context, $base-size, $limit-size-min, $limit-size-max, $property: padding-left);
}
$context: Max-width of your container
$base-size: Root font size
$limit-size-min: The minimum size
$limit-size-max: The maximum size
.selector {
scale(1400px, 16px, 5px, 20px, $property: padding-right);
scale(1400px, 16px, 5px, 20px, $property: padding-left);
}
This would scale down to 5px and up to 20px, between 5-20 it is dynamic based of vw
Try using the css properties min and max as a workaround
For example:
width: min(50vw, 200px);
means the width will be the smallest of the two values.
width: max(50vw, 200px);
means the width will be the larger of the two values.
More details here:
https://developer.mozilla.org/en-US/docs/Web/CSS/min

Div fit according image width

I have a portfolio page with a image display with zoom.
I have this code: http://codepen.io/Mpleandro/pen/LvrqJ
The div that shows the image has a class of .display, on line 13 of the HTML and the css formating for this div isline 90.
The image width will be flexible, so I what I want is to make the containing div inherit the width of image.
I tried the css property auto, inherit and min-with, but nothing works!
Could someone help me?
P.S.: I need a responsive solution.
Thanks
since 1 year has passed you may not be interested in the solution, but hope that helps someone else.
I also had a situation like that where I needed a div to be of the same width as the image and this had to be responsive.
In my case, I set a fixed width for the div
.some-div{
width: 250px;
}
I also had responsive image:
img{
display: block;
max-width: 100%;
height; auto;
}
and then I added a media query with threshold when the fixed width of the div started to affect the responsive nature and simply addedd this:
#media screen and (max-width: 917px){
.some-div{
width: 100%;
}
}
For my project the threshold was 917px when the fixed width started to affect.
I guess it is a solution that will fit everyone since width: 100% after the certain threshold will always be the width of the image if the image is responsive.
I don't know how to give you a perfect answer, but I can hopefully send you in the right direction. First, you can forget about inherit or min-width because they are not what you want.
auto is the default value, and I think that the default behaviour is very close to what you want: the width of the div adapt to its content. If this is not the current behaviour, this is because of many other reasons including the positioning of that div. The thing is, you won't have a proper centering and sizing of the <div class="display"> with only CSS, because it would need a specific explicit width declaration.
Since you already use Javascript to display/hide the good images, you could use Javascript to set the width everytime you change the image that is in the box.
My best advice would be to use existing solutions which are tested, approved and look really good. A 2 seconds Google search pointed me to Fesco which you could try.
I'm not sure if this is what you mean, but if it is, I hope it will help!
If you want your image to fill the div, but to scale with the browser, try setting the width of your div. Next, apply max-width="100%"; height: auto; to your image.
The simplest solution would be to just set .display to display: inline-block;, which would adjust its size to the contained image. If you want to be responsive as well, you need to define an upper limit via max-height: 80%, for example.
Put together, it would look like this: http://codepen.io/anon/pen/IluBt
JS line 17:
$(".display").css("display","inline-block");
CSS for .display
.display {
position: relative;;
background: rgba(255,255,255,0.5);
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
max-height:80%; /* <-- limit the height */
top:10%;
left:0;
margin:auto;
}
And to align everything nicely:
.loader {
color: red;
position: fixed;
width: 100%; height: 100%;
background: rgba(0,0,0, 1) url(../http://www.mpleandro.com.br/images/new/loader.gif) no-repeat center center;
text-align: center;
}

Image auto width in CSS for all browsers?

I have my img tag defined with some CSS as:
img
{
width: auto !important;
height: auto !important;
max-width: 100%;
}
It works just fine in some of the Mobile Browsers I have tried, as well as Google Chrome on a desktop. However, it does not seem to work in IE or FireFox. By that, I mean, as you resize the window. Take a look at a sandbox site I am working on: http://terraninstitute.com. I have the image on the home page intentionally set to be a huge picture. Also navigate to the Information (main menu) then Newcomers (side menu) and notice the map image at the bottom. On my Droid (and a few other devices I can get my hands on) as well as in Google Chrome this looks pretty good. In IE and FireFox, not so much.
Am I missing something? Conflicting style definitions? I am not finding them as of yet if it is.
TIA
You're declaring the width of your images multiple times in your document unnecessarily and declaring a max-width the wrong way. Max-width is supposed to define a max size/boundary for your images (600px, for example), if you declare max-width:100% in conjunction with width:100%, you're not really doing anything with that declaration as the images will expand 100% as it is.
Remove the width declarations from your CSS in the following lines:
line 116: delete the img declaration all together, it is not needed.
line 365: remove the max-width:100% and height:auto; attribute as they are not needed (and if you can delete the declaration all together as you can declare that elsewhere)
line 121: Now just stick with this one and just add the following:
img {
height: auto;
width:100%;
}
Bootstrap solution for responsive images:
img {
/* Responsive images (ensure images don't scale beyond their parents) */
/* Part 1: Set a maxium relative to the parent */
max-width: 100%;
/* IE7-8 need help adjusting responsive images */
width: auto\9;
/* Part 2: Scale the height according to the width, otherwise you get stretching */
height: auto;
vertical-align: middle;
border: 0;
-ms-interpolation-mode: bicubic;
}
Don't use !important
Make your CSS more speficic:
body img {
width: auto;
height: auto;
max-width: 100%;
}
in style.css line line 116, 212 and in inuit.css line 365. Remove all those.
img{
height: auto;
max-width: 100%;
}
Thats all you need.

Resources