Как прижать дочерний блок к низу родительского?
В верстке есть такой блок, фиксированной высоты, в него вложены ещё три блока, верхний и нижний — фиксированной высоты, тот, что посередине — нет. Не могу понять, как прижать нижний блок к низу родительского.
5 ответов 5
У дочернего в стилях пишите:
position: absolute; bottom: 0px;
position:relative; padding-bottom:50px;
Хм. Если размеры вам известны, то тут чистая математика. Если только средствами CSS, то можно, например, так сделать:
* < margin: 0; padding: 0; >#wrapper < width: 400px; height: 600px; border: 1px solid #900; overflow: hidden; text-shadow: 1px 1px 1px #FFFFFF; >#top < background: #999; height: 70px; text-align: center; line-height: 70px; >#center < background: #CCC; >#bottom < position: absolute; width: 400px; top: 551px; background: #999; height: 50px; text-align: center; line-height: 50px; >p
TOP Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
BOTTOM
Если размеры не известны изначально, то тут в помощь JS/jQuery.
Вёрстка. Как прижать блок к нижнему блоку?
Как прижать блок (к примеру правый блок с меню) к нижнему блоку? на примере сайта #Хэшкод как есть как хотелось бы
4 ответа 4
При позиционировании вложенного элемента absolute.
- . если у родителя значение position установлено как static или родителя нет, то отсчет координат ведется от края окна браузера.
- . если у родителя значение position задано как fixed, relative или absolute, то отсчет координат ведется от края родительского элемента.
Правильно, не некроссбраузерно будет так:
.container < border: 1px black solid; padding: 10px; >.container .block < display: inline-block; vertical-align: bottom; border: 1px black solid; >.container .left < width: 60%; margin: 0 5% 0 0; height: 500px; >.container .right
Asen, если вы верстаете кроссбраузерно, вы используете хаки. Если вы верстаете кроссбраузерно, вы не используете CSS3. Если вы верстаете кроссбраузерно, вы используете в пять раз больше времени на тестирование. Всё это ведёт к увеличению времени на вёрстку минимум в 1.5 раза, если макеты не очень сложные. Соответственно, увеличивается и ценник. Также увеличивается сложность проекта, время на корректировки. А если макеты сложные? А если нельзя использовать JS? А что будет, если вы тыкнете на iOS по лейблу? А как это исправить?
Получается, что это лохи и недалёкие ищут компромисс между сложностью, стоимостью и кроссбраузерностью. Только лохи оценивают изменение конверсии от недостаточного даунгрейда для старых браузеров. Только лохи (ну и недалёкие) сначала спросят, какова планируемая аудитория, чтобы решать, верстать кроссбраузерно или нет. Только лохи забьют на то, что у 10% пользователей проекта уголки будут не скругленными и сделают их в одну строчку за минуту, а не будут полдня резать макеты и наводить кошмар в вёрстке.
How can I send an inner to the bottom of its parent ?
The div inside another div picture and code below. Because there will be text and images of the parent div. And red div will be the last element of the parent div.
So is the code from the parent div logically placed above the child div? Are the images and text dynamically added? What’s the specific question?
9 Answers 9
But because the inner div is positioned absolutely, you’ll always have to worry about other content in the outer div overlapping it (and you’ll always have to set fixed heights).
If you can do it, it’s better to make that inner div the last DOM object in your outer div and have it set to «clear: both».
🙂 Actually i couldn’t get how we are hacking IE with symbols, thats why i thought it is IE Hacking 🙂
.parent < display: flex; flex-direction: column; justify-content: space-between; >/* not necessary, just to visualize it */ .parent < height: 500px; border: 1px solid black; >.parent div
Images, text, buttons oh my! Bottom
Browser support for flexbox — Caniuse
OMG, where have you been all my [programming] life! 😉 I love that this is so simple and doesn’t mess with positioning, and it seems to just about work in all browsers: caniuse.com/#feat=flexbox. This should be the solution and accepted answer for modern programming.
Flexbox is usually the «easy way» these days and has (nearly) great browser support and documentation. Adding the caniuse link to the answer.
Make the outer div position=»relative» and the inner div position=»absolute» and set it’s bottom=»0″ .
Yes, this works but absolute positioning breaks the «natural layout». Inner div’s height will not get included as height of parent and as the outer div gets narrower, you might see overlap with other stuff in outer div.
Here is another pure CSS trick, which doesn’t affect an elements flow.
Positioning with margin
Content to the bottom
Great! The other flex solution moved all my content out of place, this one isolates the object you want to put at the bottom from the rest. Great solution!
Brilliant! I combined this with #parent :last-child for better automation (instead of .child ). This avoids having to give the child a class name or ID, and the CSS will always apply to the last child.
You may not want absolute positioning because it breaks the reflow: in some circumstances, a better solution is to make the grandparent element display:table; and the parent element display:table-cell;vertical-align:bottom; . After doing this, you should be able to give the the child elements display:inline-block; and they will automagically flow towards the bottom of the parent.
Note : This is by no means the best possible way to do it!
Situation : I had to do the same thign only i was not able to add any extra divs, therefore i was stuck with what i had and rather than removing innerHTML and creating another via javascript almost like 2 renders i needed to have the content at the bottom (animated bar).
Solution: Given how tired I was at the time its seems normal to even think of such a method however I knew i had a parent DOM element which the bar’s height was starting from.
Rather than messing with the javascript any further i used a (NOT ALWAYS GOOD IDEA) CSS answer! 🙂
-moz-transform:rotate(180deg); -webkit-transform:rotate(180deg); -ms-transform:rotate(180deg);
Yes thats correct, instead of positioning the DOM, i turned its parent upside down in css.
For my scenario it will work! Possibly for others too ! No Flame! 🙂
Как прижать кнопку к низу блока?
Как прижать кнопку к низу блока, чтобы она всегда была внизу вне зависимости от наполнения блока контентом.
position: absolute; bottom: 0;
текст
Очень много текста Очень много текста Очень много текста Очень много текста Очень много текста Очень много текста Очень много текста
текст
1 ответ 1
Не очень понял что значит, кнопки выпадают из потока, но если имеется ввиду чтобы при растягивании блока по ширине, они всегда оставались по центру, то попробуйте обернуть кнопку в контейнер btn-cont сделать его абсолютным и на всю ширину. Внутри расположите Вашу кнопку и сделайте контейнер flex , с justify-content: center . Тем самым блок всегда будет внизу и при расширении или уменьшении родителя кнопка будет располагаться в центре. Если же имеется ввиду, чтобы текст не заезжал на кнопку, то добавьте родителю padding-bottom: (высота кнопки +- несколько пикселей) Пример ниже (без отступов):
.block < position: relative; display: inline-block; width: 200px; min-height: 320px; color: steelblue; border: 1px solid red; text-align: center; padding-bottom: 40px >.text < font-size: 20px; margin: 0 auto 0; >.btn-cont < width: 100%; height: 30px; position: absolute; bottom: 0; left: 0; display: flex; align-items: center; justify-content: center; >.button
текст
Очень много текста Очень много текста Очень много текста Очень много текста Очень много текста Очень много текста Очень много текста
текст