Как отцентрировать контент в блоке по вертикалиОпубликовано: 06.02.2013 01:47 Автор: Ogri Просмотров: 6719
На первый взгляд может показаться, что решение вынесенной в заголовок задачи тривиально: устанавливаем CSS-атрибут vertical-align:middle
- и все дела. Но не так все просто. Принцип компоновки элементов традиционно основан на масштабировании по ширине, в высоту же содержимое растягивается или сжимается в соответствии с шириной. vertical-align
удобно использовать в таблицах для центрирования содержимого ячеек, равно как и в блоках DIV с атрибутом display:table-cell
. Ожидаемого поведения при вертикальном центрировании контента можно также достичь для элементов нормального потока страницы - блоков с атрибутом display:inline-block
. Во всех же прочих случаях этот подход неприменим, поскольку большинство современных браузеров просто использует значение атрибута vertical-align
для наследования дочерними inline-элементами блока. Здесь потребуется другая методика, описанию которой и посвящена эта статья.
Сразу оговорюсь: использование этой техники подразумевает два предположения:
- Вы можете определить фиксированную высоту внутреннего блока.
- Можно присвоить внутреннему блоку абсолютное позиционирование. Как правило, это не проблема, поскольку контейнер может оставаться в общем потоке.
Если эти условия соблюдены, делаем следующее:
- В стиле контейнера определяем атрибут
position
какrelative
илиabsolute
. - Задаем фиксированную высоту дочернего блока.
- Устанавливаем в стиле дочернего блока
position:absolute
иtop:50%
, совместив тем самым его верхнюю границу с серединой родительского блока. - Присваиваем атрибуту
margin-top
дочернего блока значение, равное половине его высоты, что сдвинет дочерний блок вверх до совпадения его середины с серединой контейнера.
Пример:
<div style="position: relative;">
Контейнер
<div style="position:absolute; top:50%; height:8em; margin-top:-4em;">
Отцентрированный по вертикали дочерний блок
</div>
</div>
Вот как это выглядит в браузере:
Пример практического использования данного метода при вписывании имиджа в контейнер вы можете найти в следующей статье.
Новые
-
20.07.2020 00:53
Joomla 3: Перенаправление на ту же страницу после авторизации -
13.02.2017 14:09
Joomla: как добавить свои языковые константы или переопределить существующие -
13.02.2017 13:23
Joomla: Интегрируем reCAPTCHA v2 (NO CAPTCHA) в JComments -
23.06.2016 10:48
Единая фильтрация вывода модуля mod_jcomments_latest -
13.09.2015 13:06
Постим иллюстрированные статьи Joomla-сайта на Facebook, используя OG-теги
Популярные
-
100900
Миграция с Joomla 1.5 на Joomla 2.5. Ч.2-1. Перенос jDownloads и jComments -
72933
Joomla: Интегрируем reCAPTCHA v2 (NO CAPTCHA) в JComments -
61578
Редактирование анимированных GIF-имиджей в Photoshop CS3 -
38024
Joomla: как добавить свои языковые константы или переопределить существующие -
34361
Единая фильтрация вывода модуля mod_jcomments_latest
Авторизация
Гитара
Гостевая колонка
Последние комментарии
-
Joomla: Сливаем два сайта в один при помощи компонента J2XML
-
여성알바 29.05.2023 14:47
Eveen though slots are thee majority, table game lovers are in for a enjoyable-filled adventure.
-
-
Единая фильтрация вывода модуля mod_jcomments_latest
-
milf tube 29.05.2023 20:19
Homemade is quite a great and satisfying porn to watch because it senses casual and domestic. As ...
-
-
Миграция с Joomla 1.5 на Joomla 2.5. Ч.1. Перенос информационного наполнения
-
바카라사이트 29.05.2023 17:44
An interesting disussion іѕ worth сomment. I ԁo think that yoս оught to publish morre ⲟn thіs issue ...
-
Regen CBD 29.05.2023 12:46
I want to express my appreciation to this writer for rescuing me from such a difficulty. Just ...
-
-
Структура внутренних ссылок сайта на Joomla
-
여성밤 알바 29.05.2023 15:40
No, the version of baccarat played at on the web casinos is Punto Banco, which is purely a game of ...
-
-
Цифровые коды WEB (веб) цветов для сайта
-
Вулкан жара 29.05.2023 20:53
When someone writеs an paragraph he/she retains the thought of a user in his/her brain thɑt how a ...
-
m1bar.Com 29.05.2023 19:16
An intriguing discussion is worth comment. I do believe that you ought to publish more about this ...
-
промокод Вулкан Жара 29.05.2023 18:07
Wow, awesome blog layout! Hoᴡ long have you bеen blogging for? you make blogging look easy. The overall ...
-
미수다 29.05.2023 07:23
The casino also accepts players from lots of countries, which includes Korea, creating it accessible ...
-
pharmeasy 29.05.2023 06:39
Hi colleagues, how is the whole thing, and what you want to say regarding this piece of writing, in my ...
-
Комментарии
With top-notch content and cutting-edge analysis, you'll
never miss a beat! Get ready for an exciting season
Feel free to visit my website sport betting
000 รายการ คุณจะสามารถค้นหาสิ่งที่เหมาะกับรสนิยมของคุณ นอกจากนี้ ด้วยโบนัสและโปรโมชันมากมาย คุณจะได้รับผลตอบแทนที่มากขึ้น มา
Feel free to surf to my website ... คาสิโนออนไลน์ 168
Our site offers an exciting range of real-time games and features, as well as a secure and safe environment to
play in. Test your luck today with our exclusive
My blog; baccarat stone
x2
เลือกจากสล็อต เกมบนโต๊ะ และตัวเลือกการเดิมพันกีฬาที่น่าตื่นเต้นหลายร้อยราย การ ด้วยโบนัส โปรโมชัน และโปรแกรม VIP ที่หลากหลาย Sagame มีบางสิ่งสำหรับทุกคน มาร่วมสนุกได้แล้ววันนี้!
my homepage - sagame 168vip
We have all your favorites from slots and table games, to live dealer options.
Play for real money or just for fun - the choice is yours!
Join today to get your welcome bonus and start
Look no further than king855
casino. That is one of the most popular online casino
sites around and offers a wide range of games and promotions.
At king855, you can play classic slots, video slots, table games, poker, baccarat, and other specialty games.
Also you can enjoy sports betting on popular sports
such as for example football, basketball, and tennis.
The casino offers great bonuses and promotions like welcome bonuses, deposit bonuses,
and free spins. There is also a loyalty program where you can earn points and redeem them for rewards such as for example cashback and free spins.
It is possible to access king855 online casino on any device ?
desktop, laptop, mobile, or tablet. The website is also secure and safe, so you can be sure that your computer data is safe.
Go through the thrill of online casino gaming with king855 today!
กับเรา ที่ Sexy
Baccarat Thai เรามีตัวเลือกเกมออนไลน์ที่หลากหลายเพื่อตอบสนองความ คาดหวังของผู้เล่น เลือกจากเกมการพนันที่น่าตื่นเต้นมากมายและเริ่มชนะท ันที!
malta
4Jokers Casino คือประสบการณ์การเล่นเกมออนไลน์ที่ดีที่สุด!
เตรียมตัวให้พร้อมสำหรับชัยชนะครั้งใหญ่ในเกมสล็อต
แจ็คพอต และเกมคาสิโนคลาสสิกที่หลากหลายของเรา เข้าร่วมตอนนี้และเตรียมพร้อมสำหรับความตื่นเต้นของชีวิต
Here is my web-site สล็อต66
ด้วยโบนัส โปรโมชั่น และอื่นๆ อีกมากมาย คุณสามารถเพลิดเพลินกับเกมสล็อต รูเล็ต แบล็กแจ็ก และบาคาร่าที่คุณโปรดปรานจากที่บ้านได้อย่างสะดวกสบาย
My blog post - sa gaming บาคาร่า
Look no further than king855 casino.
This is probably the most popular online casino sites around and will be
offering a wide range of games and promotions.
At king855, it is possible to play classic slots, video slots,
table games, poker, baccarat, and other specialty games.
Also you can enjoy sports betting on popular sports such as for example football, basketball, and
tennis.
The casino offers great bonuses and promotions like welcome bonuses,
deposit bonuses, and free spins. There is also
a loyalty program where you can earn points and
redeem them for rewards such as for example cashback and free spins.
You can access king855 online casino on any device ? desktop, laptop,
mobile, or tablet. The web site can be secure and safe, so you can be sure that your data is safe.
Go through the thrill of online casino gaming with king855 today!
Spin and win on classic casino favorites such as Roulette, Blackjack, Slots, Poker and more.
Enjoy thrilling bonuses and special promotions to boost
your bankroll and make playing even more
เรานำเสนอเกมที่หลากหลายตั้งแต่สล็อตไปจนถึงแบล็คแจ็ค พร้อมโปรโมชั่นและโบนัสที่น่าตื่นเต้น เข้าร่วมกับเราวันนี้และค้นหาว่าทำไมเราถึงเป็นคาสิโนออนไลน์ที่ดีที่สุดสำหรับการชนะด้วยเงินจริง
Here is my web site; คาสิโนออนไลน์1688
เล่นสล็อตคาสิโนออนไลน์และเกมบนโต๊ะที่คุณชื่นชอบที่
CaishenWins ด้วยเกมที่มีให้เลือกมากกว่า 500 เกม คุณจะพบกับชุดค่าผสมที่ชนะได้อย่างแน่นอน ตรวจสอบโปรโมชั่นและโบนัสที่ยอดเยี่ยมของเราเพื่อโอกาสที่มากขึ้น
Feel free to surf to my blog - caishen wins
With hundreds of slots and table games, you can enjoy a thrilling gaming experience with top-notch graphics and sound effects.
Get ready for the ultimate casino adventure with Slotroma!
Also visit my webpage :: slot roma
no kyc
Experience fun, thrilling, and exhilarating playing options with
a number of the newest gaming titles in the industry.
Try your luck today!
Join mega888 and experience the ultimate online casino gaming experience.
Having an extensive selection of games, entertaining features and generous
bonuses, mega888 offers a one-of-a-kind gaming experience for
all forms of players. Register now and allow good
Play top-rated online casino game mega888 and win amazing prizes.
Like a wide selection of the most recent and greatest video slots
from leading developers. With free bonuses, daily challenges
and VIP programs, mega888 brings the best gaming experience to your
Play your favorite online casino games at Mega888 and also have an unforgettable
gaming experience! Enjoy hundreds of slots, live casino tables, and more with bonus points
and in-game rewards. Go through the thrill of winning now!
Play all of your favorite online casino games at mega888.
Like a wide range of slots, jackpot games, live dealer games and much more.
Start playing today and become in with the opportunity to win real money prizes!
Play mega888 (budtrader.com)
online with secure Malaysian online gaming!
We offer the very best gaming experience with a host of amazing promotions and
bonuses, and also top-notch customer service.
Download now and enjoy a distinctive casino gaming adventure without needing to travel!